Skip to content Skip to sidebar Skip to footer

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 b

Solution 1:

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.

Solution 2:

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

classUserProfile(models.Model):
    file = models.ForeignKey(UserFile)

Then set the AUTH_PROFILE_MODULE setting in settings.py and run syncdb.

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

Tutorial on userprofiles

Post a Comment for "Django One-to-many Relation"