0

We're building an API using Django Rest Framework where I have the following schema:

    class Main(models.Model):
        name = models.CharField(default=None, max_length=200, blank=True, null=True)
        # [...]
    
    
    class Attribute(models.Model):
        main = models.ForeignKey('Main', on_delete=models.CASCADE, related_name='attrs')
        code = models.CharField(max_length=50, null=True)
        value = models.CharField(max_length=50, null=True)

I want to build a queryset (paginated) for a list of Main objects and I would like to sort them using the "value" of certain Attribute "code".

For example, if we suppose three attributes are: "age" (8-18), "grade" ("A", "B", "C", etc.), "stars" (0-5) and Main were "students" I would like to be able to build a queryset for the list of students ordered by "age" and "grade" values.

I've tried something like:

queryset = Main.objects.filter(id__in=ids).filter(attrs__code='age').order_by('attrs_value')

Edited: Yes, actually this solution worked, but how can I deal with numeric order? I mean, "12.22" should be after "3.2".

Extra: Would I be able to reach a multiple attr order?

rodrigobb
  • 664
  • 8
  • 20

1 Answers1

1

Have you tried this:

queryset = Main.objects.filter(id__in=ids).filter(attrs__code='age').order_by('attrs__value')
Pruthvi Barot
  • 1,948
  • 3
  • 14