I have a basic Django app in which users (django's authentication built in model) and reports have a many-to-many relationship.
Django does not create a corresponding table to handle this relationship. My application is called reports
. There is an error in the admin system upon trying to create a report
and assign users to it. It tries to query the table reports_report_users
and it fails as it does not exist.
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
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 :(Django will automatically generate a table to manage many-to-many relationships. You might need a custom “through” model. The most common use for this option is when you want to associate extra data with a many-to-many relationship.
A ManyToManyField in Django is a field that allows multiple objects to be stored. This is useful and applicable for things such as shopping carts, where a user can buy multiple products. To add an item to a ManyToManyField, we can use the add() function.
You can have in your models two user classes that extend from the USER model.
It's highly recommended to set up a custom User model when starting a new Django project. Without it, you will need to create another model (like UserProfile ) and link it to the Django User model with a OneToOneField if you want to add new fields to the User model.
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.-
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With