我试图通过三个相关中间模型的字段来命令QuerySet。让我简化我当前的场景,假设我有这些模型。
class User(AbstractUser):
phone = models.CharField(max_length=20, blank=True, null=True)
city = models.CharField(max_length=50, blank=True, null=True)
address = models.CharField(max_length=150, blank=True, null=True)
about_me = models.CharField(max_length=200, blank=True, null=True)
class School(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=50, verbose_name=_(u'Name'))
email = models.EmailField(blank=True, verbose_name=_(u'Email'))
phone = models.CharField(max_length=15, blank=True,
verbose_name=_(u'Phone'))
admins = models.ManyToManyField(User,
verbose_name=_(u'Administrators'),
through='SchoolAdmins',
related_name='school_administered')
assistants = models.ManyToManyField(User,
verbose_name=_(u'Assistants'),
through='SchoolAssistants',
related_name='school_assisted')
instructors = models.ManyToManyField(User,
verbose_name=_(u'Instructors'),
through='SchoolInstructors',
related_name='school_instructed')
class SchoolAdmins(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
school = models.ForeignKey(School)
order = models.PositiveSmallIntegerField(default=0, verbose_name=_(u'Staff ordering number'))
class SchoolAssistants(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
school = models.ForeignKey(School)
order = models.PositiveSmallIntegerField(default=0, verbose_name=_(u'Staff ordering number'))
class SchoolInstructors(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
school = models.ForeignKey(School)
order = models.PositiveSmallIntegerField(default=0, verbose_name=_(u'Staff ordering number'))
注意中间模型SchoolAdmins,SchoolInstructors和SchoolAssistants中的订单字段,它用于表示在模板中呈现用户时的视图排序级别,因此,指定的顺序很重要(尽管它可以是None,zero或者甚至重复)
那就是说,我需要返回一个由中间模型的order字段排序的QuerySet。
轻松获取用户:
qs = User.objects.filter(Q(schoolassistants__school__id=school_id) |
Q(schooladmins__school__id=school_id) |
Q(schoolinstructors__school__id=school_id))
但我不确定如何根据订单字段订购查询集......这是否可能?如果可能的话,我想避免在Python中这样做......