10

我有一个看起来像这样的模型:

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

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

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

查询集将类似于:

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

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

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

4

2 回答 2

26

你可以试试:

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']
于 2013-05-22T06:42:28.123 回答
5

最简单的方法是在管理员中进行

你的模型

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)
于 2016-04-13T15:43:39.423 回答