Django ManyToMany filtering by set size or member

2019-07-17 06:03发布

问题:

I am using django to maintain a database of messages.
Among others I have the following models:

class User(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=10)

class Message(models.Model):
    id = models.IntegerField(primary_key=True)
    body = models.CharField(max_length=200)
    users = models.ManyToManyField(User)

I am trying to write a utility method that for a given user gives me the messages he (and he alone) is associated with.

i.e. for:

m1 = Message(id=1, body='Some body')
m1.save()
m2 = Message(id=2, body='Another body')
m2.save()
m3 = Message(id=3, body='And yet another body')
m3.save()

u1 = User(name='Jesse James')
u1.save()
u2 = User(name='John Doe')
u2.save()

m1.users.add(u1, u2)
m2.users.add(u1)
m3.users.add(u2)

getMessagesFor('Jesse James')

Will return only m2.
Assuming I have in user the right model instance, it boils down to one line, and I have tried these following:

    user.message_set.annotate(usr_cnt=Count('users')).filter(usr_cnt__lte=1)

Or:

    messages = Message.objects.filter(users__id__in=[user.id])

And:

    messages = Message.objects.filter(users__id__exact=user.id)

And:

    messages = Message.objects.filter(users__contains=user)

And so on... I always get both m2 AND m1.
Tried annotations, excludes, filters etc.

Can someone help me with this?

回答1:

qs = Message.objects.annotate(cc=Count('users')).filter(cc=1)

Above query will return all messages which has only single user associated with it.

To filter by user, add another filter at end to filter the annotated query according to user:

qs = Message.objects.annotate(cc=Count('users')).filter(cc=1).filter(users__id=user.id)
# if user user.id=1, this will return only m2


回答2:

Something like this maybe? (not tested)

for msg in Messages.objects.all():
    if (user in msg.users_set.all() and len(msg.users_set.all()) == 1):
        # do something