Reputation: 125
There is a model ElectoralTable
class ElectoralTable(models.Model):
name = models.CharField(max_length=250)
country_owner = models.ForeignKey(Country, on_delete=models.CASCADE)
city_owner = models.ForeignKey(City, on_delete=models.CASCADE)
address = models.CharField(max_length=400)
latitude = models.CharField(max_length=250, blank=True)
longitude = models.CharField(max_length=250, blank=True)
class Country(models.Model):
name = models.CharField(max_length=250, unique=True, blank=False)
def __str__(self):
return self.name
class Meta:
ordering = ('name',)
class City(models.Model):
name = models.CharField(max_length=400, blank=True)
country_owner = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='country')
def __str__(self):
return self.name
class Meta:
ordering = ('country_owner', 'name', )
How can I to select a city related to a country. Rigth now I receive every city on Model City but I want only to receive the cities related wiht country owner
Upvotes: 1
Views: 28
Reputation: 125
Well I found one solution to prevent save a city who doesn't belong to country it was to overwrite the clean method
def clean(self):
city = City.objects.filter(country_owner__name=self.city_owner)
city_names = []
for item in city:
city_names.append(item.name)
if not str(self.city_owner) in city_names:
raise ValidationError(_('The city doesn't belong to the country'))
Upvotes: 1