Django:检查ManytoManyField中的对象存在

时间:2015-05-06 07:01:31

标签: django python-2.7 manytomanyfield

我将ChatRoom模型设为,

class ChatRoom(models.Model):
    name = models.CharField(max_length=300)
    owner = models.ForeignKey(UserProfile)
    description = models.CharField(max_length=300)
    members = models.ManyToManyField(UserProfile,related_name='members')
    members_requested = models.ManyToManyField(UserProfile,related_name='member_requested')
    members_blocked = models.ManyToManyField(UserProfile,related_name='member_blocked')
    def __unicode__(self):
        return self.name

例如,我已将UserProfile实例添加到成员字段。

chr_obj.members.add(up_obj1,up_obj2)

如何检查UserProfile对象是否存在。我试过了, 如果chr_obj.name ='new room'

up_obj.chatroom_set.filter(name ='new room')。exists()

但它返回false。如何验证? 感谢。

1 个答案:

答案 0 :(得分:0)

您的问题可能来自错字吗?

up_obj1.chatroom_set.filter(name='new room').exists()

要检查,您可以运行:

chr_obj.members.all()