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?