如何在Django Rest中处理M2M关系 [英] How to work with M2M relationship in django-rest

查看:66
本文介绍了如何在Django Rest中处理M2M关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们从django文档中使用的有关M2M关系的模型开始,该模型使用through参数指向将充当中介的模型。

Let's start from the models used in the django docs about the M2M relationship that uses the through argument to point to the model that will act as an intermediary.

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __unicode__(self):
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, 
                                     through='Membership')

    def __unicode__(self):
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()

    class Meta:
        ordering = ['date_joined']

假设现在我想休息一下读写查看组m odel还包含每个组中的所有Person,按date_joined字段排序。我想获得的json序列化如下(成员仅用其id描述):

Assume now I want to have a rest read-write view for the Group model which contains also all the Person inside each group, ordered by date_joined field. The json serialization I would like to obtain is the following (the members are described only with their id):

{
    "id": 1, 
    "name": "U2", 
    "members": [
       20, 
       269, 
       134, 
       12,
    ]
}

我写道序列化器:

class GroupSerializer(serializers.ModelSerializer):
    members = serializers.SlugRelatedField(source='membership_set', 
                                           many=True, 
                                           read_only=False,
                                           slug_field='person_id', 
                                           required=True)

    class Meta:
        model = Group
        fields = ('id', 'name', 'members')

进行读操作时好吧,它不适合写作。我应该如何定义序列化程序,以使在上述定义的序列化下,序列化程序将继续进行:

While for read operations it works well, it doesn't for writing. How should I define the serializer so that, given the above defined serialization, it will proceed by:


  1. 创建Group对象

  2. 通过创建成员资格对象将每个成员添加到组中


推荐答案

来自此处您会看到您尝试执行的操作仅适用于读取操作。如创建者汤姆·克里斯蒂(Tom Christie)在注释。

From here you can see that what you are trying to do works only for read operations. This is a common problem for DRF, as stated by its creator, Tom Christie, in this comment.

此外,对于所需的JSON序列化,建议使用PK相关字段,如下所示<在href = http://www.django-rest-framework.org/api-guide/relations#primarykeyrelatedfield rel = nofollow>此处,尽管这对创建Group对象没有帮助和增加成员。

Also, for the JSON serialization that you want, it is recommended to use a PK related field, as shown here, though that won't help with creation of the Group object and adding of members. You will have to write that code yourself.

希望这会有所帮助。

编辑 >

通过创建成员身份将每个人添加到组中的代码段:

Code snippet for adding each person to the Group by creating Memberships:

def post_save(self, obj, created=False):
    # obj represents the Group object
    if created:
        # Test to see if the Group was successfully created
        members = self.request.DATA.get('members', None)
        if members not None:
            for id in members:
                person = Person.objects.get(id=id)
                membership, m_created = Membership.objects.get_or_create(person=person, group=obj)
                # Here you can use m_created to see if the membership already existed and to do whatever else you need.

此实现假定您已声明您的日期已加入 auto_now 。如果没有,还应该将其作为参数传递。

This implementation assumes that you have declared your date_joined with auto_now. If not, you should also pass it in as a parameter.

这篇关于如何在Django Rest中处理M2M关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆