Django binding

I have read the documentation, but still encounter errors. I have users who order catalog objects. I would like to create a query that returns all users who have an order containing a specific directory item.

Here are my models:

class Catalog(models.Model): name = models.CharField(max_length=100) price = models.IntegerField() def __unicode__(self): return self.name class Annual(models.Model): catalog = models.OneToOneField(Catalog, blank=True, null=True, related_name='annual_products') year_id = models.IntegerField(max_length=4) start_date = models.CharField(max_length=10) end_date = models.CharField(max_length=10) date = models.DateTimeField(auto_now_add=True, blank=True) def __unicode__(self): return unicode(self.year_id) class Order(models.Model): user = models.ForeignKey(User, related_name='who_ordered') select = models.ManyToManyField(Catalog, related_name='annuals_ordered', blank=True, null=True) def __unicode__(self): return unicode(self.user) 

Here is the query I tried:

  Catalog.objects.filter(order__select__annual='2014') 
+6
source share
2 answers

If you need users, you should start with users. In addition, you need to filter a specific field in the Annual, i.e. year_id.

 User.objects.filter(order__select__annual__year_id=2014) 
+12
source

If I understand your question correctly, your request is incorrect. Your Catalog model does not have an attribute name order , then how can you use it for filtering? Or am I missing nothing here?

By directly using the linked link names in the corresponding fields, you can get users using -

 # id is auto generated field or you can pass one annual_product object. User.objects.filter(who_ordered__select__annual_products__id=1) # OR annual = Annual.objects.all()[0] User.objects.filter(who_ordered__select__annual_products=annual) 

Step by step, how you can achieve the same: -

 # where 1 is the id of an one object in Catalog model. # You can pass Catalog object also to filter the users Order.objects.filter(select__id=1) # Here is the full query catalog = Catalog.objects.all()[0] orders = Order.objects.filter(select=catalog) users = [o.user for o in orders] # This loop isn't necessary. 

Now you have all the orders specific to one Catalog , from this you can get the user object using the user attribute in each order.

0
source

Source: https://habr.com/ru/post/977598/


All Articles