CodeArtist
CodeArtist

Reputation: 5684

Django Models: How to express the following logic...?

I'm facing a difficulty on a schema and i need help with the following logic.

I have a table Client and a table Rights. The table Client represents a client with some properties and the table Rights the available rights for each client.

So, i want to assign to a client a list of available rights (each user can have different rights but all are from the table Rights), how can i do it in models?

After that how can i retrieve for a Client the Rights assigned to him?

Client

name = models.CharField(max_length=256)
user = models.ForeignKey(User)
bio = models.TextField(null=True, blank=True)
website = models.URLField(null=True)

Rights

key = models.CharField(unique=True, max_length=255, db_index=True)
title = models.CharField(max_length=100, blank=True)
description = models.TextField(blank=True)

Thanks in advance!

Upvotes: 0

Views: 59

Answers (3)

Gandirham
Gandirham

Reputation: 916

Jorge, sorry I don't have enough karma to reply directly to your comment.

Question: The rights = c.rights.all() will be instance of Rights or instance of the Client?

-> Rights instances.

All Rights instances linked to the Client object.

Upvotes: 1

Akshar Raaj
Akshar Raaj

Reputation: 15211

Use ManyToManyField

class Rights(models.Model):
    key = models.CharField(unique=True, max_length=255, db_index=True)
    title = models.CharField(max_length=100, blank=True)
    description = models.TextField(blank=True)

class Client(models.Model):
    name = models.CharField(max_length=256)
    user = models.ForeignKey(User)
    bio = models.TextField(null=True, blank=True)
    website = models.URLField(null=True)
    rights = models.ManyToManyField(Rights)

You can get all the rights for a client using

c = Client.objects.get(id=1)
rights = c.rights.all()

Upvotes: 1

nicbou
nicbou

Reputation: 1056

Simply use a ManyToMany field in your Client model. After all, this is a many-to-many relationship.

If each right is unique to each client, then use a ForeignKey from a Right to a Client instead.

Upvotes: 1

Related Questions