Django how to add data to Object from queryset

六月ゝ 毕业季﹏ 提交于 2019-12-25 17:08:53

问题


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 have couple of tags or none of that. Which way is correct to do this? Can you advice me something? I need one variable with tags separated comma or objects with tags which I can use in template engine.

Views.py:

@user_passes_test(lambda u: u.is_staff, login_url='/account/login/')
def client_list(request):
    dict = {}
    dict['clients'] = Client.objects.all()

    return render(request, 'panel/client/list.html', dict)

Models.py:

class Client(models.Model):
    id = models.OneToOneField(User, on_delete=models.CASCADE, unique=True, primary_key=True)
    uuid = models.UUIDField(default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=256, unique=True)

class TagsClientChoices(models.Model):
    name = models.CharField(max_length=80, unique=True)

class TagsClientList(models.Model):
    tag_id = models.ForeignKey('TagsClientChoices')
    client = models.ForeignKey('Client', blank=True, null=True)

回答1:


By default every foreignkey has a reverse relation with _set

so you could do

for client in clients:
    for taglist in 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.

class TagsClientList(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


来源:https://stackoverflow.com/questions/35893333/django-how-to-add-data-to-object-from-queryset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!