have multiple users as one model field in many to one format django models
django, model, one-to-many, python
Solution
class Project(models.Model):
name = models.CharField(max_length=100)
users = models.ManyToManyField(User)
class Task(models.Model):
project = models.ForeignKey(Project, related_name='project_tasks')
name = models.CharField(max_length=300)
assignee = models.ForeignKey(User, related_name='tasks')
Get the the users participating in a specific project:
p = Project.objects.get(name='myproject')
users = p.users.all()
Get a project's tasks:
users = p.project_tasks.all() # Because of `related_name` in Task.project
Get All the tasks a user has, of all the projects:
u = User.objects.get(username='someuser')
u.tasks.all() # Because of `related_name` in Task.assignee
Notes:
A `ForeignKey` is a Many to One relationship. e.g. A Task belongs to only one Project - A Project can have many Tasks.
You don't need superfluous field names. `name` is better than `Project_Name`
One question at a time.
Problem
I want to create a minimalist task management app to learn Django's basics. So there will be Projects , Tasks and Users as the three big entities. - A Project can have multiple users - A Project can have multiple tasks - A task can be assigned to 1 user I can unable to figure out how to do a Many-to-One from Project - > Users using `django.contrib.auth.models.User` as my Users source. This is what I have so far, but I know it is wrong and I am unable to wrap my head around it. I tried to relate to other questions such as the one with Contestents and the one with Vulnerabilities URLS on StackOverflow. I am not sure if I have to write my own User Model, or somehow extend it. ``` class Project(models.Model): Project_Name = models.CharField(max_length=100) Project_Users = models.ManyToManyField(User) class Tasks(models.Model): Task_Name = models.CharField(max_length=300) Task_AssignedToUser = models.ForeignKey("Project_Name", through=Users) ``` Thank you for your help.