Hzmy Hzmy - 1 year ago 48
Python Question

Django many to many relationship with built in "User" model


I have a basic Django app in which users (django's authentication built in model) and reports have a many-to-many relationship.

The Problem

Django does not create a corresponding table to handle this relationship. My application is called
. There is an error in the admin system upon trying to create a
and assign users to it. It tries to query the table
and it fails as it does not exist.

models.py code

from django.db import models
from django.contrib.auth.models import User
class Report(models.Model):
name = models.CharField(max_length=30, blank=False)
users = models.ManyToManyField(User, related_name='reports')
def __unicode__(self):
return self.name

Attempted Solutions

  1. Used this link as a reference: https://docs.djangoproject.com/en/1.4/topics/db/examples/many_to_many/

  2. Ran
    manage.py syncdb
    about 300 times - ok, only once, but there were no errors and upon inspecting the SQLite db there were no additional tables created :(

Ted Ted
Answer Source

It seems like you've added to the Report model after the first sync. Thus you're dealing with a migration, which django doesn't do natively.

First, Inspect the sql output, make sure that the create table instruction for your many to many relationship is there.

python manage.py sqlall

Assuming the problem is that this is a migration, which django doesn't handle natively, you've got three options: 1) Delete all db tables for this app, then run syncdb again. 2) Manually create the tables (fairly easy to copy paste the create sql from the sqlall command) 3) Start using a migration framework like South.

In the long run you'll appreciate the investment in learning south. In the short term, deleting the DB file is the fastest.-

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download