0

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.

asked Mar 14, 2018 at 18:19
2
  • There are several ways to do it, depending on the objective. You say users should be able to have multiple projects; should projects also have multiple users? If so, you can add a ManyToManyField on Project. If not, it should be a ForeignKey. If it's a ManyToManyField, it can be on either Project or Profile, but I think semantically it makes more sense on Project, linking it to the User, and not to the Profile. Commented Mar 14, 2018 at 18:31
  • @PauloAlmeida Interesting thoughts! The ManyToManyField is exactly what I needed. I will try to find out which link makes more sense on the later use to keep stuff as simple as possible. Thank you for your help! Commented Mar 14, 2018 at 18:36

1 Answer 1

1

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

answered Mar 14, 2018 at 18:22
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, you removed the knot that was inside my brain. ;) Just to make it complete: project = models.ManyToManyField(Project)
@Tobi right! I just fixed the code.... if that answer your question, consider accepting the answer :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.