Django how to add data to Object from queryset

2024/10/7 12:19:30

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)
Answer

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://en.xdnf.cn/q/118826.html

Related Q&A

before_action ... only: how to do this in python flask? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 5 years ago.Improve…

Destroy function not destroying a frame efficiently after the first iteration in Tkinter Python

I have built a code that saves the calculated data at every iteration in a for loop and the results are stored in 3 different csv files. These saved results are read in another python code that display…

Access columns and rows of numpy.ndarray

I currently struggling with extracting certain columns and rows from a matrix stored as a numpy.ndarray. I have a list in which Ive appended these numpy.ndarrays. This list is stored in a variable name…

How to access instance object in list and display there data? in python

class Bank:def __init__(self, name, balance=0):self.name = nameself.balance = balance# def Display_details(self):# print( self.name),# print(self.balance),#### def Withdraw(self, a):# self.…

Using Class, Methods to define variables

I have a number of chemicals with corresponding data held within a database, how do I go about returning a specific chemical, and its data, via its formula, eg o2.class SourceNotDefinedException(Except…

Python Tkinter: Color changing grid of buttons?

I understand that you can make a button that can do some actions when clicked with Tkinter, but how can I just make a button that turns from one color to another when clicked? Then, from that, how do …

Writing a function that checks prime numbers

def primecheck(num): if num > 1: for i in range(2, num): if (num % i) == 0: return False breakelse: return TrueIm trying to make a function that checks if an input is prime or not. This code does …

Getting error code 1 while installing geopandas with pip

This is the error I get when trying to install geopandas using pip install geopandas. Im using Python 3.7.Collecting geopandasUsing cached https://files.pythonhosted.org/packages/24/11/d77c157c16909bd7…

Find if a sorted array of floats contains numbers in a certain range efficiently

I have a sorted numpy array of floats, and I want to know whether this array contains number in a given range. Note that Im not interested in the positions of the number in the array. I only want to k…

Django Operation error: (2026, SSL connection error: SSL_CTX_set_tmp_dh failed)

I can not start my django server after running a statement through manage.py for generating class diagrams from db. And I always get this error but I dont know how to deal with it. OperationalError: (2…