简体   繁体   中英

I want to access parent model fields using child model object in django

Hello guys I have one query in my Django project. First of all, You can see that I have two Django models named BookSeller and Book

Bookseller model

class BookSeller(models.Model):
    user_name = models.CharField(max_length=200)
    user_email = models.CharField(max_length=200)
    user_password = models.CharField(max_length=200)
    user_phone = models.CharField(max_length=100)
    user_photo = models.ImageField(upload_to='book/seller_photos/%Y/%m/%d/', blank=True)
    user_address = models.CharField(max_length=300)
    user_state = models.CharField(max_length=100)
    user_city = models.CharField(max_length=100)

    def __str__(self):
        return self.user_name

Book Model

class Book(models.Model):
    book_owner = models.ForeignKey(BookSeller, related_name='book_seller', on_delete=models.CASCADE)
    book_category = models.CharField(max_length=200) 
    book_title = models.CharField(max_length=200)
    book_price = models.IntegerField()
    book_edition = models.CharField(max_length=200)
    book_author = models.CharField(max_length=200)
    book_old = models.IntegerField()
    book_page = models.IntegerField()
    book_description = models.TextField(max_length=200)
    book_image_1 = models.ImageField(upload_to='book/book_photos/%Y/%m/%d', blank=True)
    book_image_2 = models.ImageField(upload_to='book/book_photos/%Y/%m/%d', blank=True)
    book_image_3 = models.ImageField(upload_to='book/book_photos/%Y/%m/%d', blank=True)
    book_image_4 = models.ImageField(upload_to='book/book_photos/%Y/%m/%d', blank=True)

    def __str__(self):
        return self.book_title

Want to DO: In my project I want to find books by that book seller's city. For example, if I write city name 'Silicon Valley' in my search field then it should show me all "Books" that's Sellers(BookSeller) belonging to Silicon Valley.

Query: So my query is how can I do that Django Query set, because I can't find out any query which can do this task.

If you guys have any other solution then please suggest me!!!

You can do that like this

Book.objects.filter(book_owner__user_city="Silicon Valley")

and you learn more about various kinds of joining at this link

For finding the books by some book seller's city you can simly filter the Book instances like so:

Book.objects.filter(book_owner__user_city="Silicon Valley")

One other problem I noticed is that I think you misunderstand related_name attribute in ForeignKey .

The related_name attribute specifies the name of the reverse relation from the BookSeller model back to Book model.

If you don't specify a related_name, Django automatically creates one using the name of your model with the suffix _set.

For instance more appropriate related name in your FK would be books , and without defining it would default to book_set .

book_owner = models.ForeignKey(BookSeller, related_name='books', on_delete=models.CASCADE)

Here is an example, lets assume you have 1 instance of BookSeller and 2 isntances of Book with FK to that instance of BookSeller.

my_book_seller = BookSeller(...)
my_book_1 = Book(book_owner=my_book_seller, ...)
my_book_2 = Book(book_owner=my_book_seller, ...)

Now in your case doing the my_book_seller.book_seller.all() (since you defined the related_name to be book_seller ) would return you the two Book instances belonging to my_book_seller . This doesn't make much sense. On the other hand having the related_name='books' you would get the same books by doing my_book_seller.books.all() .

You can find more info in docs .

You can get the desired results doing something like

books_by_seller_city = Book.objects.filter(book_owner__user_city='Silicon Valley')

Note the use of __ which tells the ORM to look at the referenced model attribute.

You can do with q look ups also, in that case you can add more fields in your query.

queryset = Book.objects.filter(Q(book_owner__user_city__icontains=query)|
    .................)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM