如何在DjandoREST框架中设置嵌套的相关字段序列化程序?

r55awzrz  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(290)

我正在使用django rest框架构建一个api,在该api中,我拥有以下用户制作、确认和显示对事件感兴趣的模型:
models.py

class User(AbstractBaseUser, PermissionsMixin):
    user_name = models.CharField(_("user name"), max_length=150, unique=True)
    slug = AutoSlugField(populate_from='user_name', unique=True)

class Event(models.Model):
    name = models.CharField(max_length=100, blank=False, null=False)
    owner = models.ForeignKey(User, related_name="owned_events", on_delete=models.SET_NULL, blank=True, null=True)
    confirmed = models.ManyToManyField(User, related_name="confirmed_events", blank=True)
    interested = models.ManyToManyField(User, related_name="interested_events", blank=True)

为了序列化它,我使用了我在这里和drf文档中找到的以下代码:
序列化程序.py

class UserSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = User
        fields = [
            "url",
            "user_name",
            "password",
        ]
        extra_kwargs = { "password": {"write_only": True} }

class EventSerializer(serializers.HyperlinkedModelSerializer):
    owner = UserSerializer(required=False)
    confirmed = UserSerializer(required=False, many=True)
    interested = UserSerializer(required=False, many=True)

    class Meta:
        model = Event
        lookup_field = 'slug'
        extra_kwargs = { 'url': {'lookup_field': 'slug'} }
        fields = [
            "url",
            "owner",
            "name", 
            "confirmed",
            "interested",
        ]

它可以像那样工作,但是我希望userserializer显示每个用户的已确认和感兴趣的事件,就像每个事件显示已确认和感兴趣的用户一样。我更改了序列化程序并获得了每个事件的url,如下所示:
userserializer上带有hyperlinkedrelatedfield的serializers.py

class UserSerializer(serializers.HyperlinkedModelSerializer):
    confirmed_events = serializers.HyperlinkedRelatedField(
        queryset=Event.objects.all(),
        view_name='event-detail', 
        lookup_field='slug', 
        many=True, 
        required=False
    )
    interested_events = serializers.HyperlinkedRelatedField(
        queryset=Event.objects.all(),
        view_name='event-detail', 
        lookup_field='slug', 
        many=True, 
        required=False
    )

    class Meta:
        model = User
        fields = [
            "url",
            "user_name",
            "password",
            "confirmed_events",
            "interested_events",
        ]
        extra_kwargs = { "password": {"write_only": True} }

这从用户模型中获得了以下json:

{
        "user_name": "d",
        "confirmed_events": [],
        "interested_events": [
            "http://localhost:8000/events/eqwer-2/",
            "http://localhost:8000/events/test/",
            "http://localhost:8000/events/test-2/",
            "http://localhost:8000/events/test-3/",
        ]
 }

从事件模型中:

{
    "url": "http://localhost:8000/events/eqwer-2/",
    "owner": null,
    "name": "eqwer",
    "slug": "eqwer-2",
    "confirmed": [],
    "interested": [
        {
            "user_name": "d",
            "confirmed_events": [],
            "interested_events": [
                "http://localhost:8000/events/eqwer-2/",
                "http://localhost:8000/events/test/",
                "http://localhost:8000/events/test-2/",
                "http://localhost:8000/events/test-3/",

            ]
        }
    ]
},

事件模型json很好,因为它显示每个用户的数据,但我希望用户json显示每个事件数据,而不仅仅是事件url,它类似于:

{
        "user_name": "d",
        "confirmed_events": [],
        "interested_events": [
            {
                "url": "http://localhost:8000/events/eqwer-2/",
                "owner": null,
                "name": "eqwer",
                "slug": "eqwer-2",             
            },
        ]
 }
z2acfund

z2acfund1#

为创建单独的序列化程序 interested_events 像这样:

class InterestedEventsSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        fields = ('url', 'owner', 'name', 'slug')

在你的 UserSerializer 申报 interested_events 使用上面的序列化程序:

class UserSerializer(serializers.HyperlinkedModelSerializer):
    confirmed_events = ... #
    interested_events = InterestedEventsSerializer(many=True)

    class Meta:
        model = User
        fields = [
            "url",
            "user_name",
            "password",
            "confirmed_events",
            "interested_events",
        ]
        extra_kwargs = { "password": {"write_only": True} }

相关问题