且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django如何从查询器向对象添加数据

更新时间:2023-12-04 09:47:22

默认情况下,每个外键与_set



有反向关系,所以您可以执行




client.tagsclientlist_set.all()中的标签列表:
#使用标签列表

尽管这可能不是很好,但您可能希望 prefetch_related ,并提供一个相关的名称,它将以两个查询而不是多个查询来检索结果。 p>

  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('标签_list')

客户端中的客户端:
在client.tags_list.all()中的标签列表:
#使用标签列表
/ pre>

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)

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