gpt4 book ai didi

django-models - 如何使用 Django 在查询中连接 3 个表,结合 select related 和 prefetch_lated

转载 作者:行者123 更新时间:2023-12-03 03:46:12 26 4
gpt4 key购买 nike

我有树模型

class Category(models.Model):
name = models.CharField(max_length=60)


class Product(models.Model):
description = = models.CharField(max_length=255)
category = models.ForeignKey(Category, related_name='products')


class Inventory(models.Model):
userReservation = models.ForeignKey(User)
Product=models.ForeignKey(Product related_name='products_reservation')
Quantity = models.IntegerField()

我想按类别获取用户和产品的所有产品以及库存中注册的数量

{
"id": 1,
"name": "Corbata",
"products": [{
"id": 10,
"description": "shoes",
"quantitybyInventory": 3
},
{
"id": 9,
"description": "shirt",
"quantitybyInventory": 1
}]}

我对这个类(class)有一个看法 View .py

 class inventoryList(generics.ListCreateAPIView):

queryset = Category.objects.prefetch_related('products')
serializer_class = CategorybyProductSerializer
def get_object(self):
queryset = self.queryset()
obj = get_object_or_404(queryset)
return obj

还有我的序列化器

class CategorybyProductSerializer(serializers.ModelSerializer):
products = ProductSerializer(many=True)

class Meta:
model = Category
fields = ('id', 'name', 'products')

class ProductSerializer(serializers.ModelSerializer):

class Meta:
model = Product
fields = ('id', 'description')

但是我无法显示库存表的数量

这个查询只是告诉我它

{
"id": 1,
"name": "Corbata",
"products": [{
"id": 10,
"description": "shoes"
},
{
"id": 9,
"description": "shirt"
}
]
}

最佳答案

我使用SerializerMethodField ,还有这个post

class ProductbyUserSerializer(serializers.ModelSerializer):
quantitybyInventory = serializers.SerializerMethodField(read_only=True)

def get_quantitybyInventory(self, product):
return product.products_reservation.filter(userReservation = self.context['request'].user).count()

class Meta:
model = Product
fields = ('id', 'description', 'quantitybyInventory')

关于django-models - 如何使用 Django 在查询中连接 3 个表,结合 select related 和 prefetch_lated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52069182/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com