2

The person here is a person object returned from the request

PersonAddressBook.objects.select_related().get(person = person).client 

The code above returns client object how can i rewrite it to return multiple clients. a person object may be in multiple personaddressbook so filter and not get is what am trying to do but i want the client objects without using a for-loop

there is how the other models look

class Client: #stuff here class Person: #stuff here class PersonAddressBook: client = models.ForeignKey(Client) person = models.ForeignKey(Person) 

this works but it will take longer and use more memory as it will load on my system i want use just database.

clients =[] adbook = PersonAddressBook.objects.filter(person = person).select_related() for contact in adbook: clients.append(contact.client) 

1 Answer 1

5

You can use the related_name of PersonAddressBook in the Client model:

Client.objects.filter(personaddressbook__person=person) 

According to the documentation it should be personaddressbook_set__person but for some reason currently unknown to me the related name is generated a different way.)

I prefer specifying the related_name explicitly:

class Client(models.Model): pass class Person(models.Model): pass class PersonAddressBook(models.Model): client = models.ForeignKey(Client, related_name='addressbooks') person = models.ForeignKey(Person, related_name='addressbooks') 

Now you can use the field addressbooks in the query:

Client.objects.filter(addressbooks__person=person) 
Sign up to request clarification or add additional context in comments.

6 Comments

I fixed the query. The related_name of ForeignKey used to contain a _set suffix. I'm slightly confused that this is not the case in this example.
The backwards relationship should definitely be called personaddressbook_set. Unless I'm missing something important this looks a lot like a Django bug.
ok ill try this now but dose it affect my db if i but related name ?
The related_name is just the name of the backwards relationship in the referenced model. It does not affect the database schema.
i did this to sort by self from terminal works after the 2nd try is there a better way to sort by its str or rep cos some clinets are company some are people so there self will be set choice to sort with Client.objects.filter(addressbooks__person=person).order_by('?')
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.