Query across multiple table with foreign key

Hi,

I’m pretty much sure this topic have been covered somewhere else but can’t find anything on this.

I read QuerySet API reference | Django documentation | Django and Making queries | Django documentation | Django.

The result of my queryset is the following :

SQL_Query = SELECT bill.id, client.nom, bill.detail, bill.date FROM client, bill WHERE client.nom = “something” AND bill.client = client.id

my models :

class Bill(models.Model):
    client = models.ForeignKey(Client, on_delete=models.CASCADE)
    detail = models.CharField(max_length=255, blank=True, null=True)
    date = models.DateField(blank=False)
class Client(models.Model):
    nom = models.CharField(max_length=255, blank=False, unique=True)

I tried a lot of thing. I can find the right bill_set from various way like

Bill.objects.filter(client = Client.objects.get(nom = selectClient))

But I can’t get the Client.nom.

Any idea ?

What is your question or issue that you’re trying to get addressed here?

Are you getting an error that you need assistance with?

I Edited, I pressed the post button by mistake.

If you have an instance of Client, how you do access the nom field?

If you have an instance of Bill named bill, then the linked instance of Client is bill.client.

You don’t need to create a query for that, if you have the instance of Bill that you need.

Hello Knarfel,
You must use related_name=“…”

class Bill(models.Model):
    client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='customer')
    detail = models.CharField(max_length=255, blank=True, null=True)
    date = models.DateField(blank=False)

with related_name=‘customer’, you can access all billing of a customer like this:

client = Client.objects.get(nom="something")
bills = client.customer.all()  #  Retrieves all invoices associated with this customer

Hi Ken,

I’m very sorry for wasting your time. I can’t tell you happened…

I 100% understand what you say. It was the first thing I tried and I had no result so I believed it was not working that way.

I tried then various way, mistakingly.

Sorry and thank you