在Django

时间:2018-03-15 07:32:53

标签: django-models django-rest-framework django-views

我有一个供应商表,它有以下结构:

id  vendor_name

我有另一张名为purchase的表,它具有以下结构:

id  product_id   us er_id   vendor_id

然后,默认情况下有auth_user表,其中包含用户电子邮件地址,first_name,last_name等。

我需要在django类中创建一个API,这样当我使用GET / vendor / {vendor_id}

时,我可以根据purchase表中的vendor_id列获取用户的电子邮件地址,first_name,last_name等。

注意:我需要在基于类的模型和视图中创建此API:

我的代码:

model.py

class Vendor(models.Models):
    vendor_name = models.CharField(max_length=25)

    class Meta:
        ordering = ('vendor_name',)
    def __str__(self):
        return self.vendor_name

class Purchases(models.Models):
    user = models.OneToOneFiled(User, on_delete=models.CASECADE)
    product_id = models.ForeignKey('Product', on_delete=models.SET_NULL, null=True, blank=True)
    vendor_id = models.ForeignKey('Vendor', on_delete=models.SET_NULL, null=True, blank=True)

    def __str__(self):
        return self.vendor_id

views.py

class VendorDetail(generics.RetrieveUpdateDestoryAPIView):
    queryset= Vendor.objects.all()
    serializer_class = VendorSerializer
    name = 'vendor-details'

我想要JSON响应如下。另外,我希望字段的顺序如下:

{
  "id": 1,
  "name": "group-1"
  "users": [
    {
      "id": 1,
      "email": "abc@gmail",
      "first_name": "myfirstname1",
      "last_name": "mylastname1"    },
    {
      "id": 2,
      "email": "xyz@gmail",
      "first_name": "myfirstname2",
      "last_name": "mylastname2"
    }
  ],
}

1 个答案:

答案 0 :(得分:0)

您可以使用values获取所有数据 在您的Purchases模型更改vendor_id这样的行中;

vendor_id = models.ForeignKey('Vendor', on_delete=models.SET_NULL, null=True, blank=True, related_name='vendor_purchases')

然后你可以获得这样的所有数据;注意如果您不在for循环中使用prefetch_related,则为每个用户访问数据库,但现在对于所有数据,它只访问数据库3次

vendor = Vendor.objects.get(pk=vendor_id).prefetch_related(vendor_purchases).prefetch_related(vendor_purchases__user)

user_list = []

for purchase in vendor.vendor_purchases.all():
    purchase_user = {}
    purchase_user["id"] = purchase.user.pk
    purchase_user["email"] = purchase.user.email
    purchase_user["first_name"] = purchase.user.first_name
    purchase_user["last_name"] = purchase.user.last_name
    user_list.append(purchase_user)

result={}
result["id"] = vendor.pk
result["name"] = vendor.name
result["users"] = user_list