Tobi
Tobi

Reputation: 43

Django relations between Models

What I currently have in my models is this:

class Project(models.Model):
    project_name = models.CharField(max_length=255, unique=True, blank=False)
    def __str__(self):
        return str(self.project_name)


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)  
    role = models.CharField(choices=ROLE_CHOICES, max_length=255, default='Agent')

Now my question is: Users should be able to have multiple Projects - so I obviously can't use a OneToOne-Field in the Profile-Model.

Later I want to use it for example to just show a user news which are only related to the projects he participates in.

What would be the best strategy to make this possible? Any input is highly appreciated.

Upvotes: 0

Views: 44

Answers (1)

Walucas
Walucas

Reputation: 2578

Use ManyToMany on project.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)  
    role = models.CharField(choices=ROLE_CHOICES, max_length=255, default='Agent')
    project = models.ManyToManyField(Project)

This way one profile can have as many project as he/she wants

On your view you can use this field to filter based on project

Upvotes: 1

Related Questions