django admin.py

时间:2019-02-05 09:03:14

标签: django django-admin

我正在开发一个django应用程序,其中有一个成员模型和另一个称为评论的模型。

我的members模型

class Members(models.Model):
  TITLES = (('chairman', 'Chairman'), ('secretary', 'Secretary'),)
  user = models.OneToOneField(User, on_delete=models.CASCADE)
  title = models.CharField(max_length=10, choices=TITLES, default='secretary')
  active = BooleanField(default=False)

我的reviews模型

class Reviews(models.Model):
  chairman = models.ForeignKey(Members, related_name='chairs', on_delete=models.PROTECT)
  secretary = models.ForeignKey(Members, related_name='secretaries', on_delete=models.PROTECT)
  review = models.TextField()

可能有几位主席和秘书,但是在“评论”模型上的外键下拉列表中,我只想显示处于活动状态的人员(即,将活动字段设置为True)。我试图通过在我的admin.py中添加以下内容来实现这一目标...

class ReviewsAdmin(admin.ModelAdmin):
  ...
  def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == "chairman":
      kwargs["queryset"] = Members.objects.filter(title=='chairman', active==True)
    elif db_field.name = "secretary":
      kwargs["queryset"] = Members.objects.filter(title=='secretary', active==True)
    return super().formfield_for_foreignkey(db_field, request, **kwargs)

admin.site.register(Reviews, ReviewsAdmin)

我在执行过滤器的地方遇到错误name 'title' is not defined。怎么了?

1 个答案:

答案 0 :(得分:1)

在查询中仅使用'='。

if db_field.name == "chairman":
    kwargs["queryset"] = Members.objects.filter(title='chairman', active=True)
elif db_field.name = "secretary":
    kwargs["queryset"] = Members.objects.filter(title='secretary', active=True)