最近,我一直在使用通用题字系统来帮助学生在课堂或实验室注册。但是我在Lab类中遇到了ManyToManyField的逻辑问题。
from django.db import models
from django.contrib.auth.models import User
class Day(models.Model):
name = models.CharField(max_length=20, primary_key=True)
def __unicode__(self):
return u"%s" % self.name
class LabName(models.Model):
lab_name = models.CharField(max_length=50, primary_key=True)
class Meta:
verbose_name_plural = 'LabNames'
def __unicode__(self):
return u'%s' % self.lab_name
class Lab(models.Model):
name = models.ForeignKey(LabName)
start_hour = models.TimeField()
length = models.IntegerField(help_text="Given in minutes")
classDays = models.ManyToManyField(Day)
start_date = models.DateField()
finish_date = models.DateField()
max_cap = models.SmallIntegerField(help_text="Maximun number of students")
teacher = models.ForeignKey(User, related_name="Teachers")
students = models.ManyToManyField(User)
class Meta:
verbose_name_plural = 'Labs'
def __unicode__(self):
return u"%s %s" % (self.id, self.name)
我更愿意将名为“学生”的特定群组(django.contrib.auth.models.Group
)与所有用户相关联,或者至少过滤和/或验证此字段,以便添加和查看学生,并对老师领域。
更新1:我刚才注意到,也许我可以使用可选参数limit_choices_to
过滤某个组中的用户。
问题是:
如何使用limit_choices_to
参数仅显示“学生”群组或“教师”群组中的用户?
答案 0 :(得分:2)
我会重写{'id__in' : Group.objects.all().get(name='Teachers').user_set.all()}
于:
{'groups__name' : 'Teachers' }
另外,如果您希望将管理员功能与模型分开更多(您是否知道管理员最初完全在模型中?),您可以使用formfield_for_foreignkey,这当然是一种很好的方式来保持您的模特与管理垃圾分开。
class MyModelAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "teacher":
kwargs["queryset"] = User.objects.filter(groups__name='Teacher')
if db_field.name == "students":
kwargs["queryset"] = User.objects.filter(groups__name='Student')
return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)