I am trying to construct a MultipleChoiceFilter
where the choices are the set of possible dates that exist on a related model (DatedResource
).
Here is what I am working with so far...
resource_date = filters.MultipleChoiceFilter(
field_name='dated_resource__date',
choices=[
(d, d.strftime('%Y-%m-%d')) for d in
sorted(resource_models.DatedResource.objects.all().values_list('date', flat=True).distinct())
],
label="Resource Date"
)
When this is displayed in a html view...
This works fine at first, however if I create new DatedResource
objects with new distinct date
values I need to re-launch my webserver in order for them to get picked up as a valid choice in this filter. I believe this is because the choices
list is evaluated once when the webserver starts up, not every time my page loads.
Is there any way to get around this? Maybe through some creative use of a ModelMultipleChoiceFilter
?
Thanks!
Edit:
I tried some simple ModelMultipleChoice
usage, but hitting some issues.
resource_date = filters.ModelMultipleChoiceFilter(
field_name='dated_resource__date',
queryset=resource_models.DatedResource.objects.all().values_list('date', flat=True).order_by('date').distinct(),
label="Resource Date"
)
The HTML form is showing up just fine, however the choices are not accepted values to the filter. I get "2019-04-03" is not a valid value.
validation errors, I am assuming because this filter is expecting datetime.date
objects. I thought about using the coerce
parameter, however those are not accepted in ModelMultipleChoice
filters.
Per dirkgroten's comment, I tried to use what was suggested in the linked question. This ends up being something like
resource_date = filters.ModelMultipleChoiceFilter(
field_name='dated_resource__date',
to_field_name='date',
queryset=resource_models.DatedResource.objects.all(),
label="Resource Date"
)
This also isnt what I want, as the HTML now form is now a) displaying the str
representation of each DatedResource
, instead of the DatedResource.date
field and b) they are not unique (ex if I have two DatedResource
objects with the same date
, both of their str
representations appear in the list. This also isnt sustainable because I have 200k+ DatedResources
, and the page hangs when attempting to load them all (as compared to the values_list
filter, which is able to pull all distinct dates out in seconds.
ModelMultipleChoiceFilter
. See this question. – FideismModelMultipleChoiceFilter
thoughts. I'm almost there, just feel like I'm missing a crucial piece – Vrieschoices
parameter – Pages