Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to list all values associated with all foreign keys in djongo

I am using djongo as database connector for mongoDB. I created two models called MailGroup and User. Every User is associated with a MailGroup. Each MailGroup can have multiple users. Now, I want to fetch all mailgroups and users in the following format

mailGroups = [
    {
        "id": 1,
        "name": "group - 1",
        "users": [
            {
                "name": "x1",
                "email": "y1"
            },
            {
                "name": "x2",
                "email": "y2"
            },
            {
                "name": "x3",
                "email": "y3"
            }
        ]
    },
    {
        "id": 2,
        "name": "group - 2",
        "users": [
            {
                "name": "a1",
                "email": "b1"
            },
            {
                "name": "a2",
                "email": "b2"
            }
        ]
    }    
]

I tried this and got only the mail groups, not the associated users with each group

mailGroups = MailGroup.objects.all()
serializer = MailGroupSerializer(mailGroups, many = True)

How do I do this? Here are my models

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class MailGroup(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)

class User(models.Model):
    id = models.AutoField(primary_key=True)
    email = models.CharField(max_length=255)
    name = models.CharField(max_length=255)
    mailgroup = models.ForeignKey(MailGroup, on_delete=models.CASCADE)

These are my serializers:

class MailGroupSerializer(serializers.ModelSerializer):
class Meta:
    model = MailGroup
    fields = ["id", "name"]

class RecipientSerializer(serializers.ModelSerializer):
    class Meta:
        model = Recipient
        fields = ["id", "email", "name", "mailGroup"]

>Solution :

You add the users to the MailGroupSerializer:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'name']


class MailGroupSerializer(serializers.ModelSerializer):
    users = UserSerializer(source='user_set', many=True)

    class Meta:
        model = MailGroup
        fields = ['id', 'name', 'users']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading