无法将关键字'model'解析为字段。姜戈过滤器



我试图重写过滤器,写在 Django 1.1 到 2.1 上

我有一个复杂的模型,称为Apartment,其中包括一个Location模型。Location包括District模型。

所以,我的模型代码:

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

过滤器是

district = django_filters.ModelMultipleChoiceFilter(
name="location_district",
queryset=District.objects.all(),
)

在新版本中,我将name更改为to_field_name.

当我尝试启动时,这掉了一个错误 -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

我真的不明白ModelMultipleChoiceFilter是如何工作的,以及如何从Location上获取嵌套模型District

ModelMultipleChoiceFiltername更改为field_name,这对我来说效果很好。

通过查看文档,您可以看到to_name_field将被映射到模型中的 Django 字段,因此您会收到 Django 无法"解析字段location_district"的错误,因为您的模型中没有location_district。 尽管从未使用过 DjangoFilters,但我相信如果您真的需要命名该字段,您可以将其指向location。这意味着您的过滤器需要以下内容:

district = django_filters.ModelMultipleChoiceFilter(
name="location",
queryset=District.objects.all(),
)

或者你可以试试这个,但要注意我不知道它是否会起作用

district = django_filters.ModelMultipleChoiceFilter(
name="location__district",
queryset=District.objects.all(),
)

最新更新