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
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
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 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.
Models | Django documentation, Be careful not to choose field names that conflict with the models API like clean If you change the value of the primary key on an existing object and then save it, a new So a child model does not have access to its parent's Meta class. That means the base class should subclass django.db.models.Model. The only decision you have to make is whether you want the parent models to be models in their own right (with their own database tables), or if the parents are just holders of common information that will only be visible through the child models.
You can do that like this
and you learn more about various kinds of joining at this link
Managers | Django documentation, However, if you want to use objects as a field name, or if you want to use a Using this example model, Person.objects will generate an AttributeError this example is that Manager methods can access self.model to get the model the child class override all others; then come names on the first parent class, and so on). When using multi-table inheritance, forms generated by a formset factory will contain a parent link field (by default <parent_model_name>_ptr) instead of an id field. Changing the queryset ¶ By default, when you create a formset from a model, the formset will use a queryset that includes all objects in the model (e.g., Author.objects.all() ).
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)| .................)
#16135 (Model 'Child' is inherited from 'Parent', expecting to get only , class Parent(models. I want to get the result of Child.objects.all() but I do not want to I expect the query to also work with Model Inheritance as well. Also discussed in http://groups.google.com/group/django-users/browse_thread/ thread/� See Specifying the form field for a model field for usage. deconstruct()¶ Returns a 4-tuple with enough information to recreate the field: The name of the field on the model. The import path of the field (e.g. "django.db.models.IntegerField"). This should be the most portable version, so less specific may be better. A list of positional arguments.
For finding the books by some book seller's city you can simly filter the Book instances like so:
One other problem I noticed is that I think you misunderstand
related_name attribute in
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_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
You can find more info in docs.
django.db.models.options | Django documentation, If you want to manipulate this list " "for your own use, make a copy first. deferred object loading), proxy_for_model tells us # which class this model is proxying. def get_base_chain(self, model): """ Return a list of parent classes leading to ` model` _meta # Abstract model's fields are copied to child models, hence we will� 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 .
Advanced Models - Python Django Tutorials, This is because I have worked on many versions of this chapter over time. As your data Function parameters are the model fields to use to order the QuerySet. Ordering values() returns Python dictionaries, instead of a QuerySet object: > Figure 9-1: Database tables are created for both the parent and the child model. from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Genre(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') You must define a parent field which is a ForeignKey to 'self'.
Model inheritance: Can you access a child object from the parent , Model inheritance: Can you access a child object from the parent object? "The problem I thought I had was a class starting to have too many fields only being used when the E-Commerce Payment With Django One Video using Stripe. Using add() on a relation that already exists won’t duplicate the relation, but it will still trigger signals. For many-to-many relationships add() accepts either model instances or field values, normally primary keys, as the *objs argument. Use the through_defaults argument to specify values for the new intermediate model instance(s), if needed.
django-rest-framework, django-rest-framework Getting list of all related children objects in parent's serializer Assume that, we implement a simple API and we have the following models. And we want to return a response when a particular parent is retrieved via API Meta: model = Child fields = ('url','id','child_name','parent_id') def create (self,� Sometimes, however, we will want to make use of some of the parent class behaviors but not all of them. When we change parent class methods we override them. When constructing parent and child classes, it is important to keep program design in mind so that overriding does not produce unnecessary or redundant code.