django: db - many to one

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. (default, Oct , ::)
Type "copyright", "credits" or "license" for more information. IPython 0.8. -- 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 []: In []: from blog.models import Entry , Blog In []: Entry.objects.all()
Out[]: [<Entry: eli>, <Entry: wu>, <Entry: min>] In []: Blog.objects.all()
Out[]: [] In []: blog=Blog(name='blog',entry=Entry.objects.all()[]) In []: blog
Out[]: <Blog: blog> In []: blog.save() In []: blog2=Blog(name='blog2',entry=Entry.objects.all()[]) In []: blog2.save() In []: blog3=Blog(name='blog3',entry=Entry.objects.all()[]) In []: blog3.save()

MySQL 结果:

mysql> select * from blog_entry;
+----+------+
| id | name |
+----+------+
| | eli |
| | wu |
| | min |
+----+------+
rows in set (0.00 sec) mysql> select * from blog_blog;
+----+-------+----------+
| id | name | entry_id |
+----+-------+----------+
| | blog | |
| | blog2 | |
| | blog3 | |
+----+-------+----------+
rows in set (0.00 sec)
上一篇:SpringBoot源码分析-启动时如何加载application.yml


下一篇:阿里云服务器Linux CentOS安装配置(九)shell编译、打包、部署