django one-to-many relation

In my app,I need to associate the User with a user-selected-filename

A user can only select one filename.But the same filename may be selected by many users

So,database table may be like this

auth_user(created by django.contrib.auth)

id | username | first_name | last_name | ...
1  |  bert     |  bert     | russel    |...
2  |  jon      |  jon      | snow      | ...
3  |  alice    | alice     | tanner    | ...

userfile table

id  | filename              
1   |  '/clips/summary.mp4'  
2   | '/clips/intro.mp4'    

user_userfile table

 user_id   |    userfile_id
   1       |    1
   2       |    1
   3       |    2

It seems that userfile--user is a 1 - n relation . 1 userfile can be associated with many users.

So,what should I use to represent this relationship? In class UserFile given below ,if I use

user = db.models.ForeignKey(django.contrib.auth.User)

That will only make the reverse relationship (ie n-1 for userfile--user)

class UserFile(db.models.Model):
    filename = db.models.CharField()
    user     = ??


I would really like a OneToMany field too. But the reason there is no such field in Django i believe is that this would create an FK on the table of the related model:

  1. That's sort of confusing

  2. Syncdb wouldn't be able to add the column to the existing table

The solution to add the FK on a related model is to use an "unsupported" feature:

from django.contrib.auth.models import User
models.ForeignKey(Badge, null=True, blank=True).contribute_to_class(User, 'badge')

Then you should add migrate auth_user to add the FK.

You can use userprofiles for this, although I suppose it would be a bit overkill.

class UserProfile(models.Model):
    file = models.ForeignKey(UserFile)

Then set the AUTH_PROFILE_MODULE setting in and run syncdb.

Now you can use user.get_profile().file to access the file associated with user.

Tutorial on userprofiles

Need Your Help

Minimize didFinishLaunchingWithOptions Processes on launchOptionsLocation key discovery?

ios ios5 cllocationmanager uiapplicationdelegate

I have location processing newly implemented in my app, testing in foreground and background with satisfactory results. The application is monitoring significant location changes as well as several