在Django admin中限制ManyToMany MultipleSelect的查询集

时间:2013-05-21 20:50:41

标签: django django-admin

我的模型看起来像这样:

class Event(models.Model):
    event_dates = ManyToManyField("EventDate")
    #...

class EventDate(models.Model):
    event_date = DateField()
    #...

但是,在MultipleSelect中为event_dates显示的django admin EventAdmin表单字段中,我想将查询集限制为不是过去的event_dates。

查询集将类似于:

event_date_queryset = EventDate.objects.filter(event_date__gte = datetime.date.today()) 

但是我可以在哪里设置此查询集,以便只在该字段中显示非过去的日期?

(我目前没有EventAdmin的自定义表单,但很乐意添加一个。)

2 个答案:

答案 0 :(得分:19)

你可以尝试:

event_dates = models.ManyToManyField("EventDate", limit_choices_to={'event_date__gte': date.today()})

取自https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to

但是,即使过去的某些日期仍然与Event相关联,也会显示将来的日期。

如果您还希望之前与Event相关联的所有日期,您可以按照以下方式操纵ModelForm

from datetime import date

from django.contrib import admin
from django import forms
from django.db.models import Q

from models import Event, EventDate

class EventAdminForm(forms.ModelForm):
    class Meta:
        model = Event

    def __init__(self, *args, **kwargs):
        super(EventAdminForm, self).__init__(*args, **kwargs)
        if 'event_dates' in self.initial:
            self.fields['event_dates'].queryset = EventDate.objects.filter(Q(pk__in=self.initial['event_dates']) | Q(event_date__gte=date.today()))
        else:
            self.fields['event_dates'].queryset = EventDate.objects.filter(event_date__gte=date.today())

class EventAdmin(admin.ModelAdmin):
    form = EventAdminForm
    filter_horizontal = ['event_dates']

答案 1 :(得分:4)

最简单的方法是在管理员

中执行此操作

你的模特

class Event(models.Model):
    event_dates = ManyToManyField("EventDate")
    #...

class EventDate(models.Model):
    event_date = DateField()
    #...

现在在你的管理文件中

这样做的另一个好处是,它只返回您正在查看的当前事件的事件日期,使用反向查找event__id=event_id

class EventAdmin(admin.ModelAdmin):
    def get_field_queryset(self, db, db_field, request):
        """
        If the ModelAdmin specifies ordering, the queryset should respect that
        ordering.  Otherwise don't specify the queryset, let the field decide
        (returns None in that case).
        """
        if db_field.name == 'event_dates':
            event_id = int(request.resolver_match.args[0])

            return db_field.remote_field.model._default_manager.filter(
                              event__id=event_id,
                              event_date__gte = datetime.date.today()
            )

        super().get_field_queryset(db, db_field, request)