How do I get a distinct collection of all related objects in django? -
i have setup:
class modela: name = models.textfield('name') class modelb: name = models.textfield('name') = models.foreignkey(modela)
what list of distinct modela's modelb's have. example database looks this:
a1 = modela(name='a1') a2 = modela(name='a2') a2 = modela(name='a3') b1 = modelb(name='b1', a=a1) b2 = modelb(name='b2', a=a1) b2 = modelb(name='b2', a=a3)
then result of query [a1, a3].
in 1 place, want count of list, actually, figure if can list counting trivial.
you can use combination of reverse lookups and distinct
modela.objects.filter(modelb__isnull=false).distinct("name")
you can pass positional arguments (*fields) in order specify names of fields distinct should apply. translates select distinct on sql query. here’s difference. normal distinct() call, database compares each field in each row when determining rows distinct. distinct() call specified field names, database compare specified field names.
Comments
Post a Comment