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
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"]
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']