序列化m2mfield('self')

时间:2018-08-02 07:28:37

标签: python django django-rest-framework

我在models.py中有这个模型:

class Foo(models.Model):
    bar = models.ManyToManyField('self')

如何序列化? 我正在使用该主题的一种解决方案:this,但是它们都不与M2M配合使用,都导致序列化的无限循环。我使用一行序列化程序的解决方案效果很好,除了它受到复制和粘贴的限制(听起来真可悲:))

通用model看起来像是评论的树。我希望这样的问题以前已经解决过,但是还没有找到。

2 个答案:

答案 0 :(得分:1)

我认为您不会为此找到直接解决方案,因此请尝试

class FooBaseSerializer(serializers.ModelSerializer):
    class Meta:
        fields = '__all__'
        model = Foo


class FooSerializer(FooBaseSerializer):
    bar = FooBaseSerializer(many=True)

答案 1 :(得分:0)

注意:作为一名软件工程师,我喜欢使用体系结构,并且我对分层开发方法进行了深入的研究,因此我将就层级回答它。

我建议对M2M关系使用桥表来规范化东西。无论如何,序列化许多项目都需要

serializer = SerializerNameGoesHere(AllFilteredObjectsfromModel, many=True)

将使用序列化器m2m。 这是分层方法的一个例子!

据我所知,这是解决方案

models.py

class Member(models.Model):
    member_id = models.AutoField(primary_key=True)
    member_name = models.CharField(max_length = 

class Group(models.Model):
    group_id = models.AutoField(primary_key=True)
    group_name = models.CharField(max_length = 20)
    fk_member_id = models.ForeignKey('Member', models.DO_NOTHING, 
                             db_column='fk_member_id', blank=True, null=True)

class Membership(models.Model):
    membershipid = models.AutoField(primary_key=True)
    fk_group_id = models.ForeignKey('Group', models.DO_NOTHING, 
                             db_column='fk_member_id', blank=True, null=True)
    join_date = models.DateTimeField()

serializers.py

import serializer

class AllSerializer(serializer.Serializer):
    group_id = serializer.IntegerField()
    group_name = serializer.CharField(max_length = 20)
    join_date = serializer.DateTimeField()

CustomModels.py

imports...

    class AllDataModel():
        group_id = ""
        group_name = ""
        join_date = ""

BusinessLogic.py

imports ....
class getdata(memberid):
    alldataDict = {}
    dto = []
    Member = models.Members.objects.get(member_id=memberid) #or use filter for Name
    alldataDict["MemberId"] = Member.member_id
    alldataDict["MemberName"] = Member.member_name
    Groups = models.Group.objects.filter(fk_member_id=Member)
    for item in Groups:
        Custommodel = CustomModels.AllDataModel()
        Custommodel.group_id = item.group_id
        Custommodel.group_name = item.group_name
        Membership = models.Membership.objects.get(fk_group_id=item.group_id)
        Custommodel.join_date = Membership.join_date
        dto.append(Custommodel)
    serializer = AllSerializer(dto,many=True)
    alldataDict.update(serializer.data)
    return alldataDict