本站首页    管理页面    写新日志    退出


«October 2025»
1234
567891011
12131415161718
19202122232425
262728293031


公告
 本博客在此声明所有文章均为转摘,只做资料收集使用。

我的分类(专题)

日志更新

最新评论

留言板

链接

Blog信息
blog名称:
日志总数:1304
评论数量:2242
留言数量:5
访问次数:7628292
建立时间:2006年5月29日




[Django]Relating a model to another model more than once
软件技术

lhwork 发表于 2007/2/1 14:48:10

In this example, a Person can have a mother and father -- both of which are other Person objects. Set related_name to designate what the reverse relationship is called. Model source codefrom django.db import models class Person(models.Model): full_name = models.CharField(maxlength=20) mother = models.ForeignKey('self', null=True, related_name='mothers_child_set') father = models.ForeignKey('self', null=True, related_name='fathers_child_set') def __str__(self): return self.full_name Sample API usage This sample code assumes the above model has been saved in a file mysite/models.py. >>> from mysite.models import Person # Create two Person objects -- the mom and dad in our family. >>> dad = Person(full_name='John Smith Senior', mother=None, father=None) >>> dad.save() >>> mom = Person(full_name='Jane Smith', mother=None, father=None) >>> mom.save() # Give mom and dad a kid. >>> kid = Person(full_name='John Smith Junior', mother=mom, father=dad) >>> kid.save() >>> kid.mother <Person: Jane Smith> >>> kid.father <Person: John Smith Senior> >>> dad.fathers_child_set.all() [<Person: John Smith Junior>] >>> mom.mothers_child_set.all() [<Person: John Smith Junior>] >>> kid.mothers_child_set.all() [] >>> kid.fathers_child_set.all() []


阅读全文(1636) | 回复(0) | 编辑 | 精华
 



发表评论:
昵称:
密码:
主页:
标题:
验证码:  (不区分大小写,请仔细填写,输错需重写评论内容!)



站点首页 | 联系我们 | 博客注册 | 博客登陆

Sponsored By W3CHINA
W3CHINA Blog 0.8 Processed in 0.048 second(s), page refreshed 144790970 times.
《全国人大常委会关于维护互联网安全的决定》  《计算机信息网络国际联网安全保护管理办法》
苏ICP备05006046号