python - Filter on many to many table django -
i have following show table in django. want have filter on showinfo gives me 4 result. want related shows of 4 shows without loop. because loop gives me duplicated values. want related shows of filtered show distinct without loop.
class showinfo(models.model): name = models.charfield(max_length=250) related_shows = models.manytomanyfield('self', blank=true, related_name='all_related_shows', symmetrical=true)
when working specific show, can this:
s = showinfo.objects.get(pk=id) #assuming id id of specific show s.related_shows.all() #this return shows without duplicates.
now, if want 4 results:
s.related_shows.all()[:4]
to iterate on related_show can:
for r in s.related_shows.all(): r.related_shows.all()
it not give duplicated results. but, if want results not duplicated in whole set, can use set:
all_results = [] r in s.related_shows.all(): all_results.append(show r.related_shows.all()) set(all_results) #this show set all_shows without duplicates
here info many-to-many relationships: https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/
Comments
Post a Comment