I built my first app, which lets me create new entries in a table called 'projects' For now I have the standard user model and I would like to create a new table where I can assign a user (ID or name) to one or more project-objects.
Ideally this should be a whole new table containing just entry-pairs of an ID/name of the user and the ID/name of the project. But I really don't know how I could extract an object out of the Users list and one from the projects list to put them together in a new table.
A user should be able to add a new 'project' and be automatically assigned to it.
CodePudding user response:
What I would suggest doing is to structure your models like so:
class Project(models.Model):
... other fields
users = models.ManyToManyField(User, null=True, blank=True)
As you can see here, I am utilizing ManyToMany relation which creates another table that stores project_id-user_id pairs.
In case you want to return all User objects for the project object, you should do:
project = Projects.objects.get(...)
project_users = project.users.all()
In case when you want to return related projects for the User objects, you should do:
user = User.objects.get(...)
user_projects = user.project_set.all()
For more reference, please see https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_many/