使用来自外部API的数据填充Django模型

时间:2019-11-02 07:08:08

标签: django rest api django-models

我正在尝试从外部API提取所有数据以填充Django模型。我在这里找到了类似的问题

Proper way to consume data from RESTFUL API in django

我想我需要做的就是GET请求所有数据,然后POST请求所有数据到我的模型?

但是它不能完全回答我的问题。我想从api端点加载所有数据。

到目前为止我所拥有的。

Models.py

class Bill(models.Model):
    STATUS = Choices('Open', 'Closed')
    Table_ID = models.ForeignKey(Table, default=None, on_delete=models.CASCADE)
    Bill_Status = models.CharField(choices=STATUS, default=STATUS.Open, max_length=20)
    Date_close = models.DateTimeField(default=timezone.now)

class Bill_Items(models.Model):
    Bill_ID = models.ForeignKey(Bill, default=None, on_delete=models.CASCADE)
    Description = models.CharField(max_length=50)
    Price = models.DecimalField(max_digits=10, decimal_places=2)
    Payment_Made = models.BooleanField(default=False)
    Date = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.Description

Views.py

from bill.models import Table, Bill, Bill_Items



def get_bill_data(request):

        ##### GETTING THE DATA ####

        r = requests.get('http://127.0.0.1:8000/api/table1/', data=request.GET)

         #### POSTING THE DATA ####

         data = r.json()
         # Construct the bill attributes dictionary
         bill_attributes = {
            "PK": data["PK"],
            "Description": data["Description"],
            "Price": data["Price"]
        }
        Bill_Item = Bill_Items.objects.create(**bill_attributes)

        return HttpResponse(r.text)

这似乎不起作用,如果有人有任何想法,请告诉我。

预先感谢

0 个答案:

没有答案
相关问题