问题
I am using django_select2 in my application. I would like to search and display only according to one field of a model.
models.py:
class Venue(models.Model):
venue_name = models.CharField(max_length=50)
venue_city = models.CharField(max_length=50)
venue_country = models.CharField(max_length=50)
def __str__(self):
return f"{self.venue_name}, {self.venue_city}, {self.venue_country}"
forms.py:
from django import forms
from .models import
from django_select2 import forms as s2forms
class VenueForm(forms.ModelForm):
class Meta:
model = Venue
fields = ['venue_name', 'venue_city', 'venue_country']
widgets = {
'venue_city': s2forms.ModelSelect2Widget(model=Venue,
search_fields=['venue_city__icontains']),
'venue_country': s2forms.ModelSelect2Widget(model=Venue,
search_fields=['venue_country__icontains']),
}
The above code successfully filter by venue_city
field. Nevertheless, it returns the whole __str__(self)
. How can I make it to return only the city and country fields, so that users will see only the city or country from the dropdown list of the respective <input>
s?
I need to customise only this specific instance of the widget, because I'm using the full returned string of __str__(self)
somewhere else.
An idea
Is creating extra models like so:
class VenueCity(models.Model):
venue_name = models.OneToOneField(Venue, on_delete=models.SET_NULL, null=True)
def __str__(self):
return str(self.venue_name__venue_city) #how do I return only the name?
which I'll then use in my widget a possible solution?
来源:https://stackoverflow.com/questions/61699422/django-select2-limit-the-returned-text-to-a-specific-field-in-module