1

I have this model in models.py:

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

How can I serialize it? I was using one of solutions from this topic: Django rest framework nested self-referential objects But none of them working with M2M, either causes in infinity cycle of serialization. Solution where I'm using a row of serializers works good except it's limited by copy&paste (sounds really sad :) )

Generic model mostly looks like a comment's tree. I hope such a problem was already solved before but haven't found how yet.

Chickenfresh
  • 365
  • 5
  • 15

2 Answers2

1

I don't think you will get a straight solution to this, so try this

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


class FooSerializer(FooBaseSerializer):
    bar = FooBaseSerializer(many=True)
JPG
  • 82,442
  • 19
  • 127
  • 206
0

NOTE: As a Software Engineer, I love to use Architectures and I have deeply worked on Layered Approach for Development so I am gonna be Answering it with Respect to Tiers.

I would suggest the use of a Bridge Table for M2M relationships to Normalize Stuff. Anyhow serializing many of the Items would require to

serializer = SerializerNameGoesHere(AllFilteredObjectsfromModel, many=True)

would serializer m2m. Here's an Example in Layered Approach!

As i understood the Issue, Here's the Solution

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
Syed Faizan
  • 958
  • 9
  • 19
  • Thanks for well-explained solution but it wouldn't work in my case. My refinement about "mostly like comment tree" probably lacks one detail. For simple `ForeignKey('self')`-like field there are no problems with serializers, but if each `comment` can contain sub-comments, the depth makes an access limited to some of levels . Unfortunately, I couldn't make it work with overriding drf framework for this case and iterations through cycles didnt work any good – Chickenfresh Aug 02 '18 at 23:29
  • I saw Your Other Post with the Archietecture Explained and Loved it. Simple and Organized Code! – Ibtihaj Uddin Oct 17 '18 at 08:59