django one-to-many relation
django, python
Solution
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:
That's sort of confusing
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.
Problem
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 = ?? ```