[Fixed]-Django order by multiple filtered foreign key values

1👍

I’m not sure if this is the kind of answer you’re looking for, but I would suggest adding rating and score into your Product table as foreign keys to the product attribute as opposed to the other way around. To me, this makes more sense as a model.

class Product(Model):
    name = CharField()
    score = ForeignKey(ProductAttribute)
    rating = ForeignKey(ProductAttribute)


class ProductAttribute(Model):
    key = CharField()
    value = FloatField()

This you can then order easily using:

order_by(score__value, rating__value)

The other way I think creates too much unnecessary work, especially if you don’t have too many additional product attributes.

Leave a comment