Django检查ManyToMany字段中是否有对象 [英] Django check if object in ManyToMany field
问题描述
我有一个很简单的问题要解决.我有合作伙伴模型,其中有 >= 0 个与之关联的用户:
I have quite a simple problem to solve. I have Partner model which has >= 0 Users associated with it:
class Partner(models.Model):
name = models.CharField(db_index=True, max_length=255)
slug = models.SlugField(db_index=True)
user = models.ManyToManyField(User)
现在,如果我有一个 User 对象和一个 Partner 对象,那么检查用户是否与合作伙伴关联的最 Pythonic 的方法是什么?如果 User
与 Partner
相关联,我基本上想要一个返回 True 的语句.
Now, if I have a User object and I have a Partner object, what is the most Pythonic way of checking if the User is associated with a Partner? I basically want a statement which returns True if the User
is associated to the Partner
.
我试过了:
users = Partner.objects.values_list('user', flat=True).filter(slug=requested_slug)
if request.user.pk in users:
# do some private stuff
这可行,但我觉得有更好的方法.此外,这是否容易融入装饰器,记住我需要一个命名参数(slug
)和一个请求对象(user
).
This works but I have a feeling there is a better way. Additionally, would this be easy to roll into a decorator, baring in mind I need both a named parameter (slug
) and a request object (user
).
推荐答案
if user.partner_set.filter(slug=requested_slug).exists():
# do some private stuff
这篇关于Django检查ManyToMany字段中是否有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!