如何使用Django将查询中的3个表联接在一起,将select related和prefetch_related组合

时间:2018-08-29 03:49:43

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

我有树模型

while True:

    one = input("What are you eating for breakfast? (Enter one item at a time and 'done' when done)\n")

    if one == "done":

        print ("Done")

        break

    if one.lower() == "eggs":
        quantegg = input("How many eggs? ")
        eggcalories = (int(quantegg) * 78)
    elif one.lower() == "oatmeal":
        quantoat = input("How many servings of oatmeal? ")
        oatcalories = (int(quantoat) * 120)
    elif one.lower() == "avacado":
        quantav = input("How many avacados: ")
        avcalories = (int(quantav) * 120)
    elif one.lower() == "toast":
        quantoast = input("How many pieces of toast?: ")
        toastcalories = (int(quantoast) * 70)
        butter = input("Did you add butter?")
        if butter.lower()[0] == "y":
            quantbut = input("How many servings of butter?: ")
            butcalories = (int(quantbut) * 102)
        elif butter.lower()[0] == "n":
            butcalories = (int(quantbut) * 0)
    else:
        pass

break_total =  eggcalories + oatcalories + avcalories + toastcalories + butcalories
print ("Total calories for breakfast:",break_total)

我想为用户和产品按类别获取所有产品,并在库存中注册数量。

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()

我对这堂课有看法 views.py

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

还有我的序列化器

 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')

1 个答案:

答案 0 :(得分:0)

我使用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')