0

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)

2 Answers 2

1

You can simply use .distinct()

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

@AKS - Oh yeah, forgot that. Thanks! :)
0

For each block block.flat_set().all() should give you all the flats of that block. Then you can leave only the unique ones using distinct(). All together: block.flat_set().all().distinct('flat_name')

You can read about it here: https://docs.djangoproject.com/en/1.9/topics/db/queries/#following-relationships-backward

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.