码迷,mamicode.com
首页 > 数据库 > 详细

django_4数据库2——表外键

时间:2017-05-10 20:36:42      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:reverse   obj   int   结果   交互   实现   manager   desc   style   

表关系:

  • many to one
  • many to many
  • one to one

many to one


记录是如何创建出来的?      先创建one,在在创建many,创建时加入ForeignKey

from django.db import models

# Create your models here.
class Enter(models):
    name = models.CharField(max_length=30)
    
    def __str__(self):
        return self.name
        
    __repr__ = __str__
    
class Blog(models):
    name = models.CharField(max_length=30)
    entry = models.ForeignKey(Enter)      #参数为one项的类名
    
    def __str__(self):
        return self.name
        
    __repr__ = __str__   

 

使用交互进行检索

In [1]: from blog.models import Entry, Blog

In [2]: entry1 = Entry.objects.create(name=alen)            #创建对应的one项(Entry)

In [3]: entry2 = Entry.objects.create(name=max)

In [4]: entry3 = Entry.objects.create(name=carl)

In [6]: blog1 = Blog.objects.create(name=alen_blog1, entry=entry1)  #创建对应many项

In [8]: blog1.entry          #(many)从many端进行检索到one
Out[8]: alen

In [9]: blog1.entry_id
Out[9]: 1

In [10]: entry1.blog_set        #(one)它所对应的blog(many)都有哪些
Out[10]: <django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager at 0x7f438ce2db00>

In [11]: entry1.blog_set.all()
Out[11]: <QuerySet [alen_blog1]>

 

如何把这这种对应的结果关系如何在web界面实现?

 

django_4数据库2——表外键

标签:reverse   obj   int   结果   交互   实现   manager   desc   style   

原文地址:http://www.cnblogs.com/daduryi/p/6837796.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!