Django model filter and do distinct by specific column

Viewed 338

I have two models

class Category(models.Model):
    name= models.TextField(max_length=255)
    parent = models.ForeignKey('self', null=True, blank=True)

class Brand(models.Model):
    category = models.ForeignKey(Category)
    name= models.TextField(max_length=255)

For example:

Category

         name        parent
         -------      -------
         vehicle        0
         car            1 
         motorcycle     1 
         truck          1 
         bicycle        1
         fff            0
         ....

Brand

            name      category
            ----      --------- 
            BMW        car
            BMW        truck
            BMW        bicycle
            toyota     car
            mercedes   car
            mercedes   truck
            someThing  fff
            ....

I want to create a queryset of Brand that is filtered by vehicle and to be distinct by name.

so I can create a form in my template that will have a drop down filter with all the brands related to vehicle categories with no duplicate of names

            name     category
            ----     --------- 
            BMW       car
            toyota    car
            mercedes  truck

Is there any option to do it in a simple way,or do I need to write a function for that?

I saw an example
Select DISTINCT individual columns in django? but it returns a ValuesQuerySet and I need a QuerySet, and I prefer not to use ().distinct('someItem') that is supported only on PostgreSQL.

1 Answers
Related