Reputation: 127
I tried to rewrite filters, written on Django 1.1 to 2.1
I have a complex model, called Apartment
that includes a Location
model. Location
includes the District
model.
So, there my models code:
class District(models.Model):
district_number = models.IntegerField(_('district'))
title = models.CharField(_('district name'), max_length=100)
city = models.ForeignKey(City, on_delete=models.PROTECT)
class Meta:
unique_together = ('city', 'district_number',)
def __str__(self):
return self.title
class Location(models.Model):
apartment = models.OneToOneField(Apartment, related_name='location', on_delete=models.CASCADE)
coordinate_long = models.DecimalField(max_digits=15, decimal_places=10)
coordinate_lat = models.DecimalField(max_digits=15, decimal_places=10)
zip_code = models.IntegerField(_('zip'))
district = models.ForeignKey(District, on_delete=models.PROTECT)
subway_station = models.ForeignKey(SubwayStation, on_delete=models.PROTECT)
city = models.ForeignKey(City, on_delete=models.PROTECT)
address = models.CharField(_('human readable address of apartment'), max_length=250)
def __str__(self):
return self.address
and filter is
district = django_filters.ModelMultipleChoiceFilter(
name="location_district",
queryset=District.objects.all(),
)
At new version I changed name
to to_field_name
.
When I tried to launch, this drop an error - Cannot resolve keyword 'district' into field. Choices are: apartment_type, apartment_type_id, bedrooms_count, co_ownership, date_added, descriptions, economy_effective, economy_effective_id, energy_effective, energy_effective_id, favorite_lists, financial_info, floor, id, is_published, location, manager, manager_id, photos, plan, price, publish_type, publish_type_id, rooms, rooms_count, services, square, title, video_url
I don't really understand how the ModelMultipleChoiceFilter
works, and how can I get the nested model District
from Location
on it.
Upvotes: 2
Views: 1330
Reputation: 411
Change ModelMultipleChoiceFilter
name
to field_name
, that works well for me.
Upvotes: 2
Reputation: 2046
By looking at the docs you can see that the to_name_field
is gonna be mapped out to a Django field in your model, hence why you're getting the error that Django cannot "resolve field location_district
" because there's no location_district
in your models.
Despite have never used DjangoFilters I believe that if you really need to name that field, you can point that to the location
. Meaning that your filter would like something like:
district = django_filters.ModelMultipleChoiceFilter(
name="location",
queryset=District.objects.all(),
)
Or you can try this but beware that I have no idea if it'll work
district = django_filters.ModelMultipleChoiceFilter(
name="location__district",
queryset=District.objects.all(),
)
Upvotes: 1