我正在尝试查看当前用户是否在collaborators
m2m字段中,但一直收到错误消息:
Cannot query "John Doe": Must be "Company" instance.
有人可以帮我解决条件声明吗?
models.py:
class MyUser():
name = ...
email = ...
class Company(models.Model):
user = models.ForeignKey(MyUser, null=True,
related_name='company_owner',
on_delete=models.SET_NULL)
collaborators = models.ManyToManyField(MyUser, blank=True,
related_name='company_collaborators')
name = models.CharField(max_length=120)
views.py:
def company_dash(request, username):
user = request.user
company = get_object_or_404(
Company, Q(is_active=True), username=username)
# NEED HELP HERE PLEASE
if company.user == user or company.collaborators.filter(company_collaborators=user).exists():
# do something
答案 0 :(得分:0)
完整文档为here
您可以使用
if company.user == user or company.collaborators.filter(collaborators=user):
或
if company.user == user or company.collaborators.filter(id=user.id):
我认为没有必要添加.exists()
,因为filter(collaborators=user)
返回列表要评估为False
,如果为空。