django一对多关系 [英] django one-to-many relation

查看:162
本文介绍了django一对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我需要将用户用户选择的文件名

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

-----------------------------------------
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表



user_userfile table

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

似乎 userfile - user 是一个 1 - n 关系。 1个用户文件可以与许多用户相关联。

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

那么,我应该用什么来表示这种关系?
在下面的UserFile类中,如果我使用

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)

只会产生反向关系(即 n-1 for userfile - user

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

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


推荐答案

我真的很喜欢OneToMany字段。但Django中没有这样的一个原因,我相信这样做会在相关模型的表格上创建一个FK:

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. 这有点混乱

  1. That's sort of confusing

Syncdb无法将列添加到现有表中

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

在相关模型上添加FK的解决方案是使用不支持功能:

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

从django.contrib.auth.models import / code>

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

然后你应该添加迁移auth_user 以添加FK。

Then you should add migrate auth_user to add the FK.

这篇关于django一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆