On Mon, Feb 2, 2009 at 10:11 PM, Markus T. <oberroc...@googlemail.com> wrote: > > Hi, > > I have two simple models: > > class Country(models.Model): > name = models.CharField(_("Name"), max_length=50, > unique=True) > > class Profile(models.Model): > name = models.CharField(_("Name"), max_length=50, > unique=True) > country = models.ForeignKey(Country) > > > If I want to create a list of all countries that are actually > referenced (i.e. used by at least one Profile entry), how would I code > that in Django?
If you need country_id/country_name: >>> Profile.objects.values('country__id', >>> 'country__name').select_related('country').distinct() [{'country__name': u'Country1', 'country__id': 1}, {'country__name': u'Country3', 'country__id': 3}] Which run this query: >>> Profile.objects.values('country__id', >>> 'country__name').select_related('country').distinct().query.as_sql() ('SELECT DISTINCT "b_profile"."country_id", "b_country"."name" FROM "b_profile" INNER JOIN "b_country" ON ("b_profile"."country_id" = "b_country"."id")', ()) M. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---