Skip to content Skip to sidebar Skip to footer

Django How To Add Data To Object From Queryset

I would like show list of clients and show tags assigned to them but I have problem because I have my tags in other table and I dont know how to connect data together. Clients can

Solution 1:

By default every foreignkey has a reverse relation with _set

so you could do

forclientin clients:
    fortaglistin client.tagsclientlist_set.all():
        # use taglist

Although this may not be very performant, you may want to prefetch_related and provide a related_name which will retrieve the results in two queries rather than multiple.

classTagsClientList(models.Model):
    tag_id = models.ForeignKey('TagsClientChoices')
    client = models.ForeignKey('Client', blank=True, null=True, related_name='tags_list')



dict['clients'] = Client.objects.all().prefetch_related('tags_list')

for client in clients:
    for taglist in client.tags_list.all():
        # use taglist

Post a Comment for "Django How To Add Data To Object From Queryset"