模型manytomany字段Django中的一个例外

时间:2012-08-13 15:28:47

标签: django django-models

我需要自己向模特提出请求:

class Course(models.Model):
    owner = models.ForeignKey(User, related_name='course', limit_choices_to={'userprofile__status': 'teacher'})

class Assignment (models.Model):
    course = models.ForeignKey(Course, related_name='assignment')
    admins = models.ManyToManyField(User, blank=True, null=True, limit_choices_to={'userprofile__status': 'teacher'})

我需要管理员包含没有所有者的所有用户(教师作为状态)。我尝试过Q对象但是没有成功......

1 个答案:

答案 0 :(得分:2)

我不确定你是否可以在模型上做到这一点,但如果可以的话,可以用F完成。类似的东西:

from django.db.models import Q, F

...

limit_choices_to=Q(userprofile__status='teacher') & ~Q(id=F('owner_id'))

您必须使用Q,因为您无法使用字典模式断言否定。 ~取消了第二个QF('owner_id')用于选择所有者的值。

就像我说的那样,我自己并没有尝试这样做,所以我不能说它是否会起作用。你只需要给它一个旋转,让我们知道。

相关问题