0

I have listed the models and Serializers below.

Models:

 class CustomGroup(Group):
        description = models.CharField(max_length=150, null=True, blank=True, verbose_name="Human readable name")
    
        def __str__(self):
            return self.description or self.name
    
        class Meta:
            db_table = "groups"
    


class User(AbstractBaseUser, PermissionsMixin):
        """
        Custom user model that supports email.
        """
        groups = models.ManyToManyField(
            CustomGroup,
            verbose_name=('groups'),
            blank=True,
            help_text= (
                'The groups this user belongs to. A user will get all permissions '
                'granted to each of their groups.'
            ),
            related_name="user_set",
            related_query_name="user",
            through="UserGroup"
        )
        email = models.EmailField(max_length=255, unique=True)
        is_active = models.BooleanField(default=True)
        tenant = models.ForeignKey(
            Tenant, on_delete=models.CASCADE, null=True, db_column="tenant_id", blank=True
        )
        ......
        objects = UserManager()
    
        USERNAME_FIELD = "email"
        # REQUIRED_FIELDS = ["tenant_id"]
    
        class Meta:
            db_table = "users"

class UserGroup(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    group = models.ForeignKey(CustomGroup, on_delete=models.CASCADE)
    tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, null=True)

    class Meta:
        db_table = "user_groups"

Serializers:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        fields = ("first_name","last_name")

class UserGroupSerializer(serializers.ModelSerializer):
    users = UserSerializer(many=True,read_only=True)
    class Meta:
        model = UserGroup
        fields = ('group_id','users')

I want response like this :

    {
      "group_id":
      "users": [
       {
         "first_name": "",
          "last_name":""   
       }
       ...
      ]
    ...
   ]
}

I am only getting:

 [{"group_id":1}, ...}]

How does the UserSerializer serialize the required user ids from the User model? Since user is defined as a foreign key in UserGroup does it happen automatically? or am i missing any relation between User and UserGroup?

1 Answer 1

1

Your UserGroup is only linked to one User and one Group. So you will only be able to access to one user and one group directly. (Didn't you just mispell user in your serializer ? you wrote users)

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        fields = ("first_name","last_name")

class UserGroupSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    class Meta:
        model = UserGroup
        fields = ('group_id','user')

but this will give you something like

{
    "group": "<group_pk>",
    "user": {
        "first_name": "first_name",
        "last_name": "last_name"
    }
}

If you want to associate a specific Group with all related user, it takes something different. You would need to retrieve all the Users linked to a UserGroup having the group_id of the current UserGroup.

class UserGroupSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserGroup
        fields = ('group_id', )

    def to_representation(self, instance):
        data = super().to_representation(instance)
        related_users = get_user_model().objects.filter(usergroup__group=instance.group)
        data['users'] = UserSerializer(instance=related_users, many=true).data
        return data

But, again, this may not be the most efficient way to achieve this as it will probably result in duplicated data. So you should probably consider accessing it from your "GroupSerializer". The same logic would be applied.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.