Django的rest_framework串行器具有内部关系(Django rest_framewo

2019-10-20 15:24发布

我的models.py的这儿的一部分

class Discount(models.Model):
    discount_id = models.AutoField(primary_key=True)
    discount_category = models.ManyToManyField(Category)
    discount_store = models.ManyToManyField(Store)
    ...

class Store(models.Model):
    store_id = models.AutoField(primary_key=True)
    store_company =models.ForeignKey('Company')
    store_city = models.ForeignKey('City', to_field='city_name')
    ....

serializer.py的部分在这里:,

class StoreSerializer(serializers.ModelSerializer):
class Meta:
    model = Store
    fields = ('store_location', 'store_city', 'store_name', 'store_address')


class DiscountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Discount
        fields = ('discount_description', 'discount_start', 'discount_end', discount_title', 'discount_category', 'discount_store')

当我打折创建JSON我得到这个JSON。

[{
    "discount_description": "Description here.",
    "discount_start": "2014-08-07T14:35:13Z",
    "discount_end": "2014-08-30T14:35:15Z",
    "discount_title": "Lorem İpsum",
    "discount_category": [
        3
    ],
    "discount_store": [
        1
    ]
}]

但我希望看到“discount_store”店的详细信息。 我尝试了很多关系这一点。 但是,所有的时间,我得到这个JSON。

Answer 1:

你尝试的选项添加depth到元类? 也许是这样的:

class DiscountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Discount
        fields = ('discount_description', 'discount_start', 'discount_end', 'discount_title', 'discount_category', 'discount_store')
        depth = 1


文章来源: Django rest_framework serializer with inner relationship