views:

28

answers:

2

I am working on creating a simple contest submission system using django. This is my first real django project. Basically each user can view a list of problems, submit a file, and view a results page.

Each problem can be associated with multiple contests, and different contests can use the same problem. Because of this, both problem and contest have a manyToManyField with each other. This is what is causing my problem.

Here is the initial models.py implementation I am going with:

startfile

from django.db import models

class User(models.Model):

username = models.CharField(max_length=50)
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)

class Problem(models.Model):

name = models.CharField(max_length=50)
filename = models.CharField(max_length=300)
contests = models.ManyToManyField(Contest)

class Contest(models.Model):

name = models.CharField(max_length=50)
problems = models.ManyToManyField(Problem)
date = models.DateField()

class Submission(models.Model):

user = models.ForeignKey(User)
problem = models.ForeignKey(Problem)
filename = models.CharField(max_length=300)

endfile

Is there a simple way to fix this? Or should I rethink my entire layout? I tried breaking each class into its own django app but I don't think thats how I should do it. The error I get is that Contest can not be found (because it exists lower in the file).

All advice is appreciated!

+2  A: 

You don't need a ManyToManyField in both Contest and Problem. Many-to-many fields are already bidirectional. Just put it on one - doesn't matter which.

Daniel Roseman
A: 

Djano will automatically create the reverse relation for you, so you only need to create it one end, eg.

class Problem(models.Model):
    name = models.CharField(max_length=50)
    filename = models.CharField(max_length=300)
    contests = models.ManyToManyField(Contest, related_name='problems')

related_name gives you the possibility to assign a name to the reverse relation. Without defining the relation on the Contest model, you can then access eg. a_contest.problems.all()!

lazerscience
awesome, thank you!
Dustin