Найти - Пользователи
Полная версия: Достать записи с разными Foreign Key из таблицы
Начало » Django » Достать записи с разными Foreign Key из таблицы
1
pyOut
Есть модели:
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) 
Задача:
Нужно достать 3 любых профиля причем country_id у которых не одинаковые.
Делаю запрос:
Profile.objects.select_related().order_by('?').limit(3)

Но такой запрос может вернуть профайлы у которых country_id совпадает. Можно ли как-то изменить запрос чтобы он доставал разные country_id? Если да, то как?
barabansheg
То, что придумалось сходу на коленке:
from random import choice
countries = Country.objects.all()
diff_countr = []
while 1:
    c = choice(countries)
    if c not in diff_countr:
            diff_countr.append(c)
    if len(diff_countr) > 2:
             break
profiles  = Profile.objects.filter(country__in = diff_countr)
Saturn
Вот тут посмотрите:
http://stackoverflow.com/questions/3852104/select-distinct-individual-columns-in-django
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB