本文介绍了在Django Rest框架中的回应中包含中介(通过模型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于在django休息框架中处理m2m / through模型及其演示的问题。我们来看一个典型的例子:



models.py:

  from django.db import models 

class成员(models.Model):
name = models.CharField(max_length = 20)
groups = models.ManyToManyField('Group',through ='Membership')

class Group(models.Model):
name = models.CharField(max_length = 20)

class成员资格(models.Model) :
member = models.ForeignKey('Member')
group = models.ForeignKey('Group')
join_date = models.DateTimeField()

serializers.py:

  

class MemberSerializer(ModelSerializer):
class Meta:
model = Member

class GroupSerializer(ModelSerializer):
class Meta:
model = Group

views.py:

  imports ... 

class MemberViewSet(ModelViewSet):
queryset = Mem ber.objects.all()
serializer_class = MemberSerializer

class GroupViewSet(ModelViewSet):
queryset = Group.objects.all()
serializer_class = GroupSerializer

当获取成员的实例时,我成功地收到了所有成员的字段及其组 - 但是我只有



换句话说,我 expect 可以收到:

  {
'id':2,
'name':'some member',
'groups ':[
{
'id':55,
'name':'group 1'
'join_date':34151564
},
{
'id':56,
'name':'group 2'
'join_date':11200299
}
]
}

请注意 join_date


$ b $我尝试过这么多的解决方案,包括当然,没有人似乎给出了一个正确的答案 - 我需要做什么来包括这些额外的字段?我发现它更直接与django-tastypie但有一些其他问题,并喜欢休息框架。

解决方案

如何。 ....



在您的MemberSerializer上,定义一个字段,如:

  groups = MembershipSerializer(source ='membership_set',many = True)

然后你的会员序列化器你可以创建这个:

  class MembershipSerializer(serializers.HyperlinkedModelSerializer):

id = serializers.Field(source ='group.id')
name = serializers.Field(source ='group.name')

class Meta:
model = Membership

fields =('id','name','join_date')

这具有创建一个序列化值的组合的整体效果,组作为其所需的成员资源,然后使用自定义序列化器来提取所需的位o显示。



编辑:由@bryanph评论, serializers.field 已重命名为 serializer.ReadOnlyField 在DRF 3.0中,所以这应该是:

  class MembershipSerializer(serializers.HyperlinkedModelSerializer )

id = serializers.ReadOnlyField(source ='group.id')
name = serializers.ReadOnlyField(source ='group.name')

Meta:
model = Membership

fields =('id','name','join_date')

任何现代化的实现


I have a question about dealing with m2m / through models and their presentation in django rest framework. Let's take a classic example:

models.py:

from django.db import models

class Member(models.Model):
    name = models.CharField(max_length = 20)
    groups = models.ManyToManyField('Group', through = 'Membership')

class Group(models.Model):
    name = models.CharField(max_length = 20)

class Membership(models.Model):
    member = models.ForeignKey('Member')
    group = models.ForeignKey('Group')
    join_date = models.DateTimeField()

serializers.py:

imports...

class MemberSerializer(ModelSerializer):
    class Meta:
        model = Member

class GroupSerializer(ModelSerializer):
    class Meta:
        model = Group

views.py:

imports...

class MemberViewSet(ModelViewSet):
    queryset = Member.objects.all()
    serializer_class = MemberSerializer

class GroupViewSet(ModelViewSet):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

When GETing an instance of Member, I successfully receive all of the member's fields and also its groups - however I only get the groups' details, without extra details that comes from the Membership model.

In other words I expect to receive:

{
   'id' : 2,
   'name' : 'some member',
   'groups' : [
      {
         'id' : 55,
         'name' : 'group 1'
         'join_date' : 34151564
      },
      {
         'id' : 56,
         'name' : 'group 2'
         'join_date' : 11200299
      }
   ]
}

Note the join_date.

I have tried oh so many solutions, including of course Django Rest-Framework official page about it and no one seems to give a proper plain answer about it - what do I need to do to include these extra fields? I found it more straight-forward with django-tastypie but had some other problems and prefer rest-framework.

解决方案

How about.....

On your MemberSerializer, define a field on it like:

groups = MembershipSerializer(source='membership_set', many=True)

and then on your membership serializer you can create this:

class MembershipSerializer(serializers.HyperlinkedModelSerializer):

    id = serializers.Field(source='group.id')
    name = serializers.Field(source='group.name')

    class Meta:
        model = Membership

        fields = ('id', 'name', 'join_date', )

That has the overall effect of creating a serialized value, groups, that has as its source the membership you want, and then it uses a custom serializer to pull out the bits you want to display.

EDIT: as commented by @bryanph, serializers.field was renamed to serializers.ReadOnlyField in DRF 3.0, so this should read:

class MembershipSerializer(serializers.HyperlinkedModelSerializer):

    id = serializers.ReadOnlyField(source='group.id')
    name = serializers.ReadOnlyField(source='group.name')

    class Meta:
        model = Membership

        fields = ('id', 'name', 'join_date', )

for any modern implementations

这篇关于在Django Rest框架中的回应中包含中介(通过模型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 13:51