Python系列视频教程: Django【13讲】第九讲 数据库使用多对一映射
三种关系
many2one
many2many
one2one
我们今天着重看看many2one
python %django_home%\bin\django-admin.py startproject csvt04
cd csvt04
python %django_home%\bin\django-admin.py startapp blog
修改models.py
from django.db import models
# Create your models here.
class Entry(models.Model):
name=models.CharField(max_length=30)
def __unicode__(self):
return self.nameclass Blog(models.Model):
name=models.CharField(max_length=30)
#many2one(Blog:Entry)
entry=models.ForeignKey(Entry)
def __unicode__(self):
return self.name
D:\test\mysite\csvt04>python manage.py syncdb
下面操作数据
D:\test\mysite\csvt04>python manage.py shell
Python 2.7.2 (default, Jun 24 2011, 12:21:10) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from blog.models import Entry,Blog
>>> entry1=Entry.objects.create(name='alen')
>>> entry1
<Entry: alen>
>>> entry2=Entry.objects.create(name='max')
>>> entry3=Entry.objects.create(name='carl')
>>> blog1=Blog.objects.create(name='alen_blog 1',entry=entry1)
>>> blog1
<Blog: alen_blog 1>
>>> blog2=Blog.objects.create(name='alen_blog 2',entry=entry1)
>>> blog2
<Blog: alen_blog 2>
>>>
>>> blog1.entry
<Entry: alen>
>>> blog2.entry
<Entry: alen>
>>> entry1.blog_set
<django.db.models.fields.related.RelatedManager object at 0x019C52D0>
>>> entry1.blog_set.all()
[<Blog: alen_blog 1>, <Blog: alen_blog 2>]
>>>
注意这里使用了blog_set
我们在命令中完成了,如何在web界面里面显示这些呢?
下面一节再见