Queryset Django - according to parameters date in weight compartment - django

I'm trying to get a result where my data from the database is sorted first by weight and then by date.
My models.py look like this:
class Example(models.Model):
date_created = models.DateTimeField(auto_now_add=True)
weight = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(3)])
If I add in my object:
class Meta:
ordering = ['-date_created ']
and in the queryset will filter out after the weight I get the result as in the picture below?
How to get such a result using only query, or only using the class in the models.py file? The picture shows what I would like to get.

Just add another list element:
class Meta:
ordering = ['-weight', 'date_created']
So first it will order by weight descending and then by date_created ascending.
More you can find in Django docs.

Related

Django two parameter filter query with foreign key

My Django models look like this:
class User(models.Model):
userid = models.CharField(max_length=26,unique=True)
#some more fields that are currently not relevant
class Followers(models.Model):
user = models.ForeignKey('User',related_name='usr')
coins = models.IntegerField()
followers = models.CharField(max_length=26, null=True, blank=True)
I would now like to make a filter query in my Followers table selecting every entry where users have ID x and followers have ID y (I expect to get one result from the query).
To visualize what I have tried and know won't work is this:
queryfilter = Followers.object.filter(followers=fid, user=uid)
and this:
queryfilter = Followers.object.filter(followers=fid, user__userid=uid)
In the end I would like to access the coins:
c = queryfilter.coins
It may be possible that I cannot do it with one single query and need two, since I am trying to do a filter query with two tables involved.
Firstly, I have modified your 'Followers' model (for naming convention).
models.py
class Follower(models.Model):
user = models.ForeignKey('User', related_name='followers')
coins = models.IntegerField()
key = models.CharField(max_length=26, null=True, blank=True)
Your queryset should be ..
views.py
#coins
coins = Follower.objects.filter(key=fid, user__userid=uid).get().coins

Django OrderBy using ManyToMany table

I have the models:
class Category(models.Model):
description = models.CharField(unique=True, max_length=200)
class Car(models.Model):
categorys = models.ManyToManyField(Category)
Constantly new cars are added.
I'd like to get the last 20 categories that had a car of her type added.
I got to set up a filter, but when I got to order by I could not get it anymore.
Since I can not close any logic I will not put what I have tried here.
Updating
I add 3 cars:
Car 1 have 2 categories (cat1 and cat2)
Car 2 have 3 categories (cat2, cat20, cat3)
Car 3 have 2 categories (cat4, cat1, cat90)
I need to get:
cat1, cat2, cat3, cat4, cat20, cat90 and others...
So you have this models:
class Category(models.Model):
description = models.CharField(unique=True, max_length=200)
class Car(models.Model):
categorys = models.ManyToManyField(Category)
According to this phrase:
I'd like to get the last 20 categories that had a car of her type
added.
at first we have to find the car:
car = Car.objects.get("""your parameters""")
Then we have to find categories:
category = car.category_set.all()[:20]
Try this
UPD
When you get all Cars and Category that you need, you can get to any of category object.
categories = Cars.objects.filter("""your filter""").select_related('categorys')
for category in categories.categorys_set():
print(category.description)
I use extra() function to solve the problem.
See code blow:
class School(models.Model):
...
tag = models.ManyToManyField(Tag)
def tags(self):
meta = self.tag.through._meta
db_table = meta.db_table
primary_key = meta.pk.name
order_by = [db_table + '.' + primary_key]
return list(self.tag.extra(order_by=order_by).values_list('name', flat=True))
By adding order by to sql statement to make results order by pk of through (if not specified django will create a table for you automaticly) table.
Hope this will be helpful.

basic filtering in django using queryset

model.py
class Venue(models.Model):
place = models.CharField(max_length=50)
venue_Name = models.CharField(max_length=100)
rent = models.IntegerField()
parking_area = models.IntegerField()
def __unicode__(self):
return self.venue_Name
i want to filter this model using places which is selected in a droupdown list in one page when press filter display the model values from the database. though i read django doc i didnt understand the process of filtering
This is the part in the documentation you should be looking at - https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters
The query that filters model values from the database is:
Venue.objects.filter(place='<dropdown-select>')
Venue.objects.filter(place= a[0])
a[0] being the value received from drop-down list

Django select all values() with nullable related fields

I have models like this:
class Vendor(models.Model):
title = models.CharField()
class Product(models.Model):
...
vendor = models.ForeignKey(Vendor, null=True, blank=True)
stock = models.ManyToManyField(Supplier, through='Stock')
class Stock(models.Model):
in_stock = models.BooleanField(default=True)
supplier = models.ForeignKey('catalog.Supplier', related_name='supplier_stock')
product = models.ForeignKey('catalog.Product', related_name='product_stock')
priority = models.IntegerField(default=0)
I designed models like this, because one Product can be supplied by different suppliers, and I need to know, what supplier exactly has this Product in stock.
So, in my view I want to get all results in values, to reduce number of queries and some specific logic. Also it duplicates me Product row with different Stock, by in python I group them up.
In my view I use:
Product.objects.all().values(
'id', 'title', 'vendor_code', 'vendor__title', 'price',
'product_stock__in_stock', 'stock__title', 'stock__id', 'stock__priority')
Because of INNER JOIN and null=True for Vendor related model, it returns me not all records for Product model. It just returns values where Vendor reference is set.
If I use 'vendor' instead of 'vendor__title' it returns me more results, than previous one, because in vendor field I can get {...'vendor': *id goes here*...} or {...'vendor': None...}, but I need the vendor__title value there. So any suggestions, how to achieve this?
Thanks in advance
Changed from vendor__title to product_stock__product__vendor__title helped me to fix my problem.

Selecting distinct nested relation in Django

To describe the system quickly, I have a list of Orders. Each Order can have 1 to n Items associated with it. Each Item has a list of ItemSizes. Given the following models, which have been abbreviated in terms of fields for this question, my goal is to get a distinct list of ItemSize objects for a given Order object.
class ItemSize(models.Model):
name = models.CharField(max_length=10, choices=SIZE_CHOICES)
class Item(models.Model):
name = models.CharField(max_length=100)
sizes = models.ManyToManyField(ItemSize)
class OrderItem(models.Model):
order = models.ForeignKey(Order)
item = models.ForeignKey(Item)
class Order(models.Model):
some_field = models.CharField(max_length=100, unique=True)
So... if I have:
o = Order.objects.get(id=1)
#how do I use the ORM to do this complex query?
#i need o.orderitem_set.items.sizes (pseudo-code)
In your current set up, the answer by #radious is correct. However, OrderItems really shouldn't exist. Orders should have a direct M2M relationship with Items. An intermediary table will be created much like OrderItems to achieve the relationship, but with an M2M you get much simpler and more logical relations
class Order(models.Model):
some_field = models.CharField(max_length=100, unique=True)
items = models.ManyToManyField(Items, related_name='orders')
You can then do: Order.items.all() and Item.orders.all(). The query you need for this issue would be simplified to:
ItemSize.objects.filter(item__orders=some_order)
If you need additional data on the Order-Item relationship, you can keep OrderItem, but use it as a through table like:
class Order(models.Model):
some_field = models.CharField(max_length=100, unique=True)
items = models.ManyToManyField(Items, related_name='orders', through=OrderItem)
And you still get your simpler relationships.
ItemSize.objects.filter(items__orderitems__order=some_order)
Assuming you have reverse keys like:
ItemSize.items - reverse fk for all items with such size
Item.orderitems - reverse for all orderitems connected to item
Item.orders - you can guess ;)
(AFAIR that names would be choose by default, but I'm not sure, you have to test it)
More informations about reverse key queries are available in documentation.