Home > Enterprise >  How can i order queryset by another model data?
How can i order queryset by another model data?

Time:07-30

I have three models and i wanna order Products.objects.all() by is_it_good from ProductsRating model. How can i do it?

I was traing something like:

qs = Products.objects.annotate(
        biggest_rating = Max('productsrating__is_it_good')
    ).order_by('biggest_rating')

but then i get an error "Cannot resolve keyword 'productsrating' into field"

models.py

class CusUser(AbstractUser):
   pass

class Products(models.Model):
   name = models.CharField(max_length=300)
   category = models.CharField(max_length=300)
   cost = models.IntegerField()

class ProductsRating(models.Model):
   is_it_good = models.IntegerField(validators=[MaxValueValidator(0), MinValueValidator(5)])
   whose_rated = models.ForeignKey(CusUser, on_delete=models.CASCADE)

CodePudding user response:

Product and ProductRating are not related through a field/key, so you can't order Product objects based on ProductRating.

You can modify the Product model to include a ForeignKey to ProductsRatings like the following:

class Products(models.Model):
   name = models.CharField(max_length=300)
   category = models.CharField(max_length=300)
   cost = models.IntegerField()
   rating = models.ForeignKey(ProductsRating, on_delete=models.SET_NULL)

class ProductsRating(models.Model):
   is_it_good = models.IntegerField(validators=[MaxValueValidator(0), MinValueValidator(5)])
   whose_rated = models.ForeignKey(CusUser, on_delete=models.CASCADE)

Then, your queryset would look like this:

qs = Products.objects.annotate(
        biggest_rating = Max('rating__is_it_good')
    ).order_by('biggest_rating')
  • Related