Django - 获取带有子对象的父对象

时间:2017-09-22 14:13:56

标签: django django-rest-framework

我是Django的新手,所以我可能因为术语而错过了这个答案。

我正在尝试使用子对象获取父对象,我有:

#models.py
class Category(models.Model):
    name = models.CharField(max_length=255)
    sub_category = models.ForeignKey(SubCategory)
    title = models.CharField(max_length=255, null=True)


#serializer.py
class CategorySerializer(serializers.ModelSerializer):

    class Meta:
        model = Category
        fields = '__all__'

#views.py
Product.objects.all().filter(sub_category__category_id=category_id).select_related()
products_serializer = ProductSerializer(products, many=True)

    return Response({
        'data': products_serializer.data
    })

我正在尝试在我已经拥有的子对象中获取父 category 对象。

提前致谢:)

1 个答案:

答案 0 :(得分:0)

您已拥有父对象,可以通过每个对象访问它:

products = Product.objects.all().filter(sub_category__category_id=category_id)
for product in products:
  parent = product.parent  # You already have it

为了更好的性能,请将您的查询更改为

Product.objects.all().filter(sub_category__category_id=category_id).select_related('parent')

如评论所述,您可以通过序列化程序来完成:

class ProductItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductItem

class ProductSerializer(serializers.ModelSerializer):
    product_items = ProductItemSerializer(many=True, read_only=True)

    class Meta:
        model = Product

class CategorySerializer(serializers.ModelSerializer):
    products = ProductSerializer(many=True, read_only=True)

    class Meta:
        model = Category

现在只需将类别,产品和商品嵌套