Home > front end >  How to access an element of a model after a join in Django?
How to access an element of a model after a join in Django?

Time:06-29

My post is similar to this one except I can't access an item : Stackoverflow : How to make an Inner Join in django?

I want to display in an Html the locomotive number and the name of the customer who owns this locomotive. But they are in different tables.

Here is my models.py

class Client(models.Model):
    client_name = models.CharField(max_length=100, null=False, unique=True)

    def __str__(self):
        return self.client_name


class Locomotive(models.Model):
    locomotive_number_id = models.CharField(max_length=50, null=False, unique=True)
    locomotive_asset_id = models.CharField(max_length=50, null=False, unique=True)
    locomotive_client = models.ForeignKey(Client, null=False, on_delete=models.CASCADE)

    def __str__(self):
        return self.locomotive_number_id

Here is my views.py

def settings(request):

    my_clients = Client.objects.values_list('client_name', flat=True)
    my_locomotives = Locomotive.objects.select_related('locomotive_client')
    return render(request, 'home/settings.html', context={"my_clients": my_clients,"my_locomotives": my_locomotives})

if I print my_locomotives.query I get this :

print(str(my_locomotives.query))
SELECT 
 "foo_bar_locomotive"."id",
 "foo_bar_locomotive"."locomotive_number_id",
 "foo_bar_locomotive"."locomotive_asset_id",
 "foo_bar_locomotive"."locomotive_client_id",
 "something1_something2_client"."id",
 "something1_something2_client"."client_name"
FROM "foo_bar_locomotive"
 INNER JOIN "something1_something2_client" ON ("foo_bar_locomotive"."locomotive_client_id" = "something1_something2_client"."id")

Here is the html code that allows me to display the list of locomotives. Except that I can't display the name of the customer who owns the locomotive.

{% for elements in my_locomotives %}
    <option value="{{elements}}">{{elements}} - {{elements.client_name}}</option>
{% endfor %}

How can I do to display this:

Locomotive N° 550XXXYYY - CUSTXXXYYY

CodePudding user response:

If I understood correctly what you wanted to achieve, then you just have to do elements.locomotive_client.client_name in your template to get your client name. You'd then have something like that :

{% for elements in my_locomotives %}
    <option value="{{elements}}">Locomotive N°{{elements.locomotive_number_id}} - {{elements.locomotive_client.client_name}}</option>
{% endfor %}
  • Related