zoukankan      html  css  js  c++  java
  • django: db

    models 模块中的对象有三种对应关系:多对一,多对多,一对一。本讲说明多对一关系。

    blog/models.py:

    from django.db import models
    
    class Employee(models.Model):
        name = models.CharField(max_length=20)  # map 'name' field to db
    
        def __unicode__(self):
            return self.name
    
    class Entry(models.Model):
        name = models.CharField(max_length=20)
    
        def __unicode__(self):
            return self.name
    
    class Blog(models.Model):
        name = models.CharField(max_length=20)
        entry = models.ForeignKey(Entry)        # Many-To-One Map: Blogs - Entry
    
        def __unicode__(self):
            return self.name

    Debug 查看使用方式:

    [root@bogon csvt03]#  ipython manage.py shell
    reload ipy_profile_none
    reload ipy_user_conf
    Python 2.7.5 (default, Oct  9 2013, 22:06:47)
    Type "copyright", "credits" or "license" for more information.
    
    IPython 0.8.4 -- An enhanced Interactive Python.
    ?         -> Introduction and overview of IPython's features.
    %quickref -> Quick reference.
    help      -> Python's own help system.
    object?   -> Details about 'object'. ?object also works, ?? prints more.
    
    In [1]:
    
    In [2]: from blog.models import  Entry , Blog
    
    In [3]: Entry.objects.all()
    Out[3]: [<Entry: eli>, <Entry: wu>, <Entry: min>]
    
    In [4]: Blog.objects.all()
    Out[4]: []
    
    In [5]: blog=Blog(name='blog',entry=Entry.objects.all()[0])
    
    In [6]: blog
    Out[6]: <Blog: blog>
    
    In [7]: blog.save()
    
    In [8]: blog2=Blog(name='blog2',entry=Entry.objects.all()[1])
    
    In [9]: blog2.save()
    
    In [10]: blog3=Blog(name='blog3',entry=Entry.objects.all()[0])
    
    In [11]: blog3.save()

    MySQL 结果:

    mysql> select * from blog_entry;
    +----+------+
    | id | name |
    +----+------+
    |  1 | eli  |
    |  2 | wu   |
    |  3 | min  |
    +----+------+
    3 rows in set (0.00 sec)
    
    mysql> select * from blog_blog;
    +----+-------+----------+
    | id | name  | entry_id |
    +----+-------+----------+
    |  1 | blog  |        1 |
    |  2 | blog2 |        2 |
    |  3 | blog3 |        1 |
    +----+-------+----------+
    3 rows in set (0.00 sec)
  • 相关阅读:
    搞笑汉文化
    學習.Net(c#)打印打印結構
    學習.Net(c#)打印調用打印界面
    在Windows下Svn架設總結
    OpenFileDialog、SaveFileDialog常用屬性、對話框用法及得到系統特殊文件夾路徑
    c# FontDialog、ColorDialog、FolderBrowserDialog常用屬性
    學習.Net(c#)打印頁面設置
    學習.Net(c#)打印多頁打印
    學習.Net(c#)打印打印預覽
    C# 記錄程序運行時間
  • 原文地址:https://www.cnblogs.com/exclm/p/3360307.html
Copyright © 2011-2022 走看看