Tips for connecting multiple queries in a Django view

Hello, I have encountered a specific issue that I am trying to address. I am developing a tasking system based on three models: the taskings model, the extended user model (profile), and the default User model in Django. My goal is to showcase the usernames of individuals assigned tasks through the sales_extras field, which is an extension of the User model.

Below are my models:

class Sales_taskings(models.Model):
sales_status= (
    ('p1','Phase 1'),
    ('p2','Phase 2'),
    ('p3','Phase 3'),
    ('p4','Phase 4'),
)
task_id = models.AutoField(primary_key=True)
sales_extras= models.ManyToManyField('sales.Sales_extras')
sales_project= models.ForeignKey('sales.Sales_project',on_delete=models.CASCADE)
description = models.TextField(max_length=200 , default='your notes' )
date_time = models.DateTimeField(auto_now=True)
status = models.TextField(max_length=10, choices= sales_status ,default='p1')


class Sales_extras(models.Model):
    role= (
        ('sm','sales_manager'),
        ('s','sales'),
    )
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    user_type = models.TextField(max_length=500, choices= role)

Here is my view with context:

@login_required
def sales_taskboard(request):
    authentication_classes = [SessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated]
    sales_extras_id = Sales_taskings.objects.values('sales_extras').get('username')
    print(Sales_taskings.objects.values('sales_extras'))
    usernames = User.objects.values('username').filter(id__in=sales_extras_id)
    print(usernames) 
    context = {
    'sales_task': Sales_taskings.objects.all(),
    'sales_extras': Sales_taskings.objects.values('sales_extras'),
    'usernames': usernames
    }
    return render(request, 'sales/taskboard.html',context)

As I am new to Django, the above represents my attempts at extracting usernames. I believe there should be a predefined query method that would allow me to establish a connection between my sales_takings model, sales_extras model, and ultimately the User model.

Your assistance in this matter would be greatly appreciated!

Answer №1

Each instance of Sales_taskings contains a ManyToManyField called "sales_extras" that, when accessed, provides a queryset of all associated Sales_extras. Since each Sales_extras is linked to a User, you can utilize these attributes in your template.

Scenario

context = {
    'sale_tasks' : Sales_taskings.objects.all()
}

Template

{% for sale in sale_tasks %}
    <h4>{{ sale.description }}</h4>
    <ul>
        {% for extra in sale.sales_extras.all %}
            <li>{{ extra.user }}</li>
        {% endfor %}
    </ul>
{% endfor %}

This approach may be inefficient as it requires querying for every sale and then querying again for every extra. You can enhance this by using prefetch_related.

context = {
    'sale_tasks' : Sales_taskings.objects.prefetch_related('sales_extras__user')
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Python with Selenium to interact with a "disabled" input field on a website (specifically Bet365)

In my quest to simplify my sports betting process, I am looking to automate the filling of stake and clicking "place bet". So far, I have successfully automated the login, match/bet type search, and selection. However, sending keys to the stake input field ...

Experiencing difficulties when attempting to deploy script to AWS Lambda

My current challenge involves executing a script that utilizes Selenium and specifically webdriver. driver = webdriver.Firefox(executable_path='numpy-test/geckodriver', options=options, service_log_path ='/dev/null') The problem I am ...

The order of iteration in Python for sets

Currently, I am analyzing two large files (in the order of Gigabytes), each containing a set of keys and their corresponding values. There are some overlapping keys between the two files, but with different corresponding values. My objective is to create n ...

Looking to retrieve information from a dataframe in a specific row

Here is the data that I currently have: Year Month 2003 06 2003 09 I need to extract this data in the following format: (('2003', '06'),('2003','09')) ...

Converting JSON information into a structured database table

Seeking assistance with preprocessing a JSON file generated by YouTube's iframe API. The goal is to transform this JSON data into a pandas dataframe format, where each key from the JSON becomes a separate column and every recorded "event" translates t ...

function that recursively obtains a list of multiples

Question: Create a recursive function called get_list_of_multiples(numbers, m) that accepts a list of integers and an integer as arguments. This function should return a list of multiples of m from the input list in the same order. If there are no multiple ...

Python code encounters a Selenium error while trying to click the video button

Struggling to automate the playback of my math online video through Selenium, but encountering a problem. Other elements on the page load before the video with the play button appears. I need a way to automatically trigger that button without any delays. ...

Initiate a Python reboot script within a separate command prompt's window

Is there a way to restart a different script in a separate shell? I have a script that sometimes gets stuck waiting to read email from Gmail and IMAP. From another script, I would like to restart the main one without interrupting the second script's e ...

Can someone explain the purpose of the sel.open('/') statement in this code snippet?

What is the purpose of using the sel.open('/') command? sel = selenium('localhost', 4444, '*firefox', 'http://www.google.com/') sel.start() sel.open('/') sel.wait_for_page_to_load(10000) sel.stop() Could ...

Using JSON.load with a one-liner JSON isn't going to give you the desired result

I am dealing with JSON data that comes in two different formats - one is a single line, the other is formatted nicely. JSON A: {"id":1, "name":"BoxH", "readOnly":true, "children":[{ "id":100, "name":"Box1", "readOnly":true, "children":[ { "id":1003, "nam ...

Converting a row to a column vector based on a particular condition in Python

In this code, positive values are selected from a matrix along with their corresponding indices. The current output shows these positive values in a row vector format. However, the desired output is to have the positive values presented in a column vector ...

Insufficient Memory: Not enough space available to allocate 3.33 GiB for an array containing (15500, 2, 240, 240, 1) elements of type int16

Running my code on the latest version of PyCharm, I am using a Windows 7 64-bit system with 16GB of RAM and... Python version: 3.7.7 (default, May 6 2020, 11:45:54) [MSC v.1916 64 bit (AMD64)] I am attempting to load numerous NIFTI images from the BraTS ...

Error encountered when trying to import a file from a specific directory in Python: `ModuleNotFoundError`

Encountering a moduleNotFoundError issue while trying to import a file from the root directory. Here is the directory structure for my Flask App: index.py auth_ - server.py Pages - home.py I can successfully import home.py from the Pages directory, b ...

Is there a way to eliminate duplicates in pandas that only occur when they are repeated in the following iteration?

I am struggling with a question that is a bit unclear, so I think it would be best to illustrate what my input and output data look like. Despite my efforts, I keep hitting a roadblock every time. Input: X Y 1 a 2 b 3 c 4 a 5 b 6 c 7 a ...

Steps for reusing a selenium browser sessionIs it possible to reuse

I'm facing an issue while trying to access a pre-existing selenium browser session from a separate python process. The reuse logic works perfectly within the same python script, but fails when separated into a different script, displaying the followin ...

Graph the results of a set of linear inequalities

Two arrays of numbers ranging from -1 to 1 have been generated: a = 2*np.random.sample(100)-1 and b = 2*np.random.sample(100)-1. These arrays represent a system of linear inequalities defined by: a[i]*x + b[i]*y <= 1 for i = 0,1,..., 99 The solution ...

Incorporating positional adjustments to data points

Currently, I am trying to find a method to specify an X-Y offset for plotted data points. As I am new to Altair, I appreciate your patience. Here is the scenario: I have a dataset that records daily measurements for 30 individuals. Each person can log mul ...

Exploring comprehensive NetworkManager connection details with python-dbus

My goal is to use python to query dbus and interact with NetworkManager in order to determine if a connection is set up to automatically connect to a network. When using the nmcli tool to examine a NetworkManager connection, the output includes details lik ...

Python script for extracting OTP from Twilio SMS

Currently, I am diving into a web automation project using the selenium python-pytest framework. The challenge I'm facing involves the generation of an OTP after entering my phone number, which then needs to be retrieved and inputted into a text box o ...

What could be causing the parameters in my function to malfunction?

In my function, I am aiming to generate the initials of each name. For instance, LeBron James would produce LJ. def get_initials(first_name, last_name): first_initial = first_name[0] second_initial = last_name[0] print(first_initial + second_ ...