Associate classes with django-filters


Associate classes with django-filters



Bonjour, I have a question regarding django-filters. My problem is:
I have two classes defined in my models.py that are:


class Volcano(models.Model):
vd_id = models.AutoField("ID, Volcano Identifier (Index)",
primary_key=True)
[...]

class VolcanoInformation(models.Model):

# Primary key
vd_inf_id = models.AutoField("ID, volcano information identifier (index)",
primary_key=True)

# Other attributes
vd_inf_numcal = models.IntegerField("Number of calderas")
[...]

# Foreign key(s)
vd_id = models.ForeignKey(Volcano, null=True, related_name='vd_inf_vd_id',
on_delete=models.CASCADE)



The two of them are linked throught the vd_id attribute.



I want to develop a search tool that allows the user to search a volcano by its number of calderas (vd_inf_numcal).



I am using django-filters and for now here's my filters.py:


from .models import *
import django_filters

class VolcanoFilter(django_filters.FilterSet):

vd_name = django_filters.ModelChoiceFilter(
queryset=Volcano.objects.values_list('vd_name', flat=True),
widget=forms.Select, label='Volcano name',
to_field_name='vd_name',
)

vd_inf_numcal = django_filters.ModelChoiceFilter(
queryset=VolcanoInformation.objects.values_list('vd_inf_numcal', flat=True),
widget=forms.Select, label='Number of calderas',
)


class Meta:
model = Volcano
fields = ['vd_name', 'vd_inf_numcal']



My views.py is:


def search(request):
feature_list = Volcano.objects.all()
feature_filter = VolcanoFilter(request.GET, queryset = feature_list)

return render(request, 'app/search_list.html', {'filter' : feature_filter, 'feature_type': feature_type})



In my application, a dropdown list of the possible number of calderas appears but the search returns no result which is normal because there is no relation between VolcanoInformation.vd_inf_numcal, VolcanoInformation.vd_id and Volcano.vd_id.



It even says "Select a valid choice. That choice is not one of the available choices."



My question is how could I make this link using django_filters ?
I guess I should write some method within the class but I have absolutely no idea on how to do it.



If anyone had the answer, I would be more than thankful !









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to add background colour in existing image using Swift?

Moria Casán

How to make file upload 'Required' in Contact Form 7?