首先,这是我要限制的模型:
问题课:
class Question(models.Model):
title = models.CharField(
max_length = 200,
verbose_name = "Question title")
description = models.TextField(
verbose_name = "Question description")
block = models.ForeignKey(
to=Block,
null=True,
on_delete=models.SET_NULL,
verbose_name='Subject part to which this question belongs')
timestamp = models.DateTimeField(
auto_now_add=True,
verbose_name='Date at which the question was added')
包含我要限制的问题的一对一字段的海报类:
class Poster(models.Model):
title = models.CharField(
max_length = 200,
verbose_name = "The poster's title")
description = models.TextField(
verbose_name = "The poster's description")
authors = models.CharField(
max_length = 200,
verbose_name = "Authors' names")
image = models.ImageField(
upload_to = 'images',
verbose_name = 'Poster image')
block = models.ForeignKey(
to = Block,
null = True,
on_delete = models.SET_NULL,
verbose_name = 'The subject part to which the poster belongs')
associated_question = models.OneToOneField(
Question,
null=True,
blank=True,
on_delete=models.SET_NULL,
unique=True,
verbose_name='Question associated to this poster')
我想做的是限制“ associated_question”字段在管理员中显示的选项。我的意思是,例如,如果我只是想在管理员中显示时间戳超过某个限制的问题,我该怎么做?
非常感谢您。如果我错过了理解我的问题所必需的东西,请问我。如有必要,我很乐意提供更多信息。
答案 0 :(得分:1)
如果您希望默认情况下限制admin中的列表,则可以覆盖get_queryset
并过滤查询集,如下所示:
编辑:要过滤associated_question
下拉表单字段,您可以使用formfield_for_foreignkey
class PosterAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super(PosterAdmin, self).get_queryset(request)
timestamp_limit = datetime.now() - datetime.timedelta(minutes=5)
return qs.filter(associated_question__timestamp__gt=timestamp_limit)
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
if db_field.name == "associated_question":
timestamp_limit = datetime.now() - datetime.timedelta(minutes=5)
kwargs["queryset"] = Question.objects.filter(timestamp__gt=timestamp_limit)
return super(PosterAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
限制问题列表
class QuestionAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super(QuestionAdmin, self).get_queryset(request)
timestamp_limit = datetime.now() - datetime.timedelta(minutes=5)
return qs.filter(timestamp__gt=timestamp_limit)