Search code examples
djangouniquemodels

django model return unique values


I have two classes in my models:

class Block(models.Model):
    block_name = models.CharField(max_length=20)

class Flat(models.Model):
    block = models.ForeignKey(Block)
    flat_name = models.CharField(max_length=20)

It gives me for example blocks with following names:

block1
block2
block3

and flats with following names:

pink_flat FK to block1
red_flat FK to block2
yellow_flat FK to block3
pink_flat FK to block2
pink_flat FK to block3

Question:

What function should I create in Block class so I can return all Flat unique names e.g. for above example I would like to return pink_flat, red_flat, yellow_flat and skip the fact pink_flat occurs more than once.

So, basically I would like to return unique flat_names for each Block

I know I can create function in my Block class so I can filter Flats:

def flats_related(self):
        return Flat.objects.filter(block=self.id)

Solution

  • You can simply use .distinct()

    Flat.objects.order_by('flat_name').distinct('flat_name')
    

    **EDIT: ** Above code will work only for PostgreSQL.