T
T
tarp202022-04-10 20:22:50
Django
tarp20, 2022-04-10 20:22:50

How to check the existence of an M2M relation??

models:

class User(models.Model):
    ...
    group = models.ManyToManyField(
        Group, related_name="users_group", verbose_name="The User Group"
    )

class Group(models.Model):
    ....

How to check if the group is empty in the serializer (that is, there are no links to User)

My version :
class GroupSerializer(serializers.ModelSerializer):
    
    empty = serializers.SerializerMethodField()
    class Meta:
        ...
        
    def get_empty(self, obj):
        return not User.objects.filter(group=obj).exists()


But maybe there is an even better way.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question