dimanche 28 juin 2015

How to make two Django models with cross relationship?

I need two Django models: first with Users, second with Projects.

Between them I need many-to-many relationship with an additional field(s).

How to make the below code working?

from django.db import models

class User(models.Model):

    name = models.CharField('Name', max_length=50)
    projects = models.ManyToManyField(Project, through='UserProjects')

    def __str__(self):
        return self.name

class Project(models.Model):

    name = models.CharField('Name', max_length=50)
    users = models.ManyToManyField(User, through='UserProjects')

    def __str__(self):
        return self.name

class UserProjects(models.Model):

    user = models.ForeignKey(User)
    project = models.ForeignKey(Project)
    is_active = models.BooleanField('Active')

At the end User.projects should return Projects for specified User and in the same way Project.users should return Users for specified Project.

Aucun commentaire:

Enregistrer un commentaire