Django rest_framework serializer with inner relati

2019-08-12 03:33发布

问题:

Here part of my 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')
    ....

Here part of my 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')

When I create JSON for discount I get this 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
    ]
}]

But I want to see store details in "discount_store". I tried a lot of relationship for this. But all the time I get this JSON.

回答1:

Did you try to add the option depth to the Meta class? Maybe like this:

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