Error with ManyToManyField relation in Django

I am creating a kanban django model to my project, but i already tried a lot of things, i have read the django.docs, but i didn't find anything.

ERRORS: tasks_management.Account.projects: (fields.E339) 'AccountProjects.owner' is not a foreign key to 'Project'. tasks_management.AccountProjects: (fields.E336) The model is used as an intermediate model by 'tasks_management.Account.projects', but it does not have a foreign key to 'Account' or 'Project'.


from django.contrib.auth.models import User
from django.db import models

class Project(models.Model):
    project_name = models.CharField(max_length=50)  

    def __str__(self): 
        return self.project_name

class Account(models.Model):
    username = models.CharField(max_length=50)
    email = models.EmailField(max_length=254)
    password = models.CharField(max_length=30)
    projects = models.ManyToManyField(
        Project, 
        through='AccountProjects',
        through_fields=('contributors', 'owner'),
        blank=True
    )

    def __str__(self):
        return self.username

class AccountProjects(models.Model):
    owner = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='owner_project')
    contributors = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='contributors_project')

# 
# class Board(models.Model):
# project_name = models.ForeignKey(Project, on_delete=models.CASCADE)
# 
# def __str__(self):
# return self.project_name.project_name
# 
# class Column(models.Model):
# column_name = models.CharField(max_length=30)
# board_name = models.ForeignKey(Board, on_delete=models.CASCADE)
# order_position = models.IntegerField(default=1)
# 
# def __str__(self):
# return self.column_name
# 
# class Task(models.Model):
# task_name = models.CharField(max_length=50)
# description = models.TextField()
# creation_date = models.DateField(auto_created=True)
# updated_date = models.DateField(auto_now=True)
# column_name = models.ForeignKey(Column, on_delete=models.CASCADE)
# 
# def __str__(self):
# return self.task_name

I read the docs, but i didn't find anything, the database requirements are:

a account doesn't need a project to be instantiated a project does need a account to be instantiated a project has 1 owner, and multiple contributors

a project has 1 board a board has multiple columns a task has 1 column

I think that many to many attribute/entity is expecting a Foreign Key to Project model, and that's what generating your error. Perhaps you may need to rethink your models a little. For example, a project will always have an owner and contributors, so you may add these attributes to Project model instead of Account, and that many to many field would be added in Project as well (a project has single owner and many contributors).

Then, if you want to get all project a single user is participating you could use "get_related" methods to pull that QuerySet.

Вернуться на верх