表关系:
- 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界面实现?
时间: 2024-10-07 05:16:14