Drwhite
Drwhite

Reputation: 1695

How to retrieve elements that have the same foreign key from a list?

I have those 2 models:

class Country(models.Model):
    country_id = models.CharField(max_length=30,primary_key=True)
    country_name = models.CharField(max_length=255)

class City(models.Model):
    city_id = models.CharField(max_length=30,primary_key=True)
    city_name = models.CharField(max_length=255)
    city_country = models.ForeignKey(Country)

I have a list of cities in my request.POST (as string concatenation of cities ids):

list_cities = concat_ids.split(',')

for every city_id in the list above, there is a foreign key to the country. Is there a simple way to verify if the list of cities are in the same country (i.e have the same ForeignKey 'city_country')?

Upvotes: 1

Views: 51

Answers (2)

augustomen
augustomen

Reputation: 9749

This would be the same as doing a simple distinct().count(), however, distinct doesn't work in every database (see the note in distinct()). So you may get the value list and transform it into a set, which should be only 1 in length:

country_set = set(City.objects.filter(id__in=list_cities).values_list('city_country', flat=True))
if len(country_set) == 1:
     #...

Upvotes: 0

alecxe
alecxe

Reputation: 473893

This will return the list of country ids for every city in list_cities:

country_ids = City.objects.values_list('city_country_id', flat=True).filter(id__in=list_cities)

Then, check that all elements in the list are the same:

country_ids.count(country_ids[0]) == len(country_ids)

Upvotes: 1

Related Questions