django models 关系

1.一对多/多对一

class Entry(models.Model):
    name=models.CharField(max_length=50)
    def __str__(self):
        return self.name

class Blog(models.Model):
    name=models.CharField(max_length=20)
    entry=models.ForeignKey("Entry",on_delete=True)     #多对一关键字
    def __str__(self):
        return self.name
>>> from fir.models import Entry,Blog
>>> entry1=Entry(name='entry1')            #create entry one
>>> entry2=Entry(name='entry2')
>>> entry3=Entry(name='entry3')
>>> blog1=Blog(name='blog1',entry='entry1')    #create blog, but failed
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "Z:\xxxxxx\models\base.py", line 477, in __init__
    _setattr(self, field.name, rel_obj)
  File "Z:\xxxxxx\related_descriptors.py", line 197, in __set__
    self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "'entry1'": "Blog.entry" must be a "Entry" instance.             
>>> e=Entry.objects.all()
>>> e
<QuerySet []>
>>> entry1.save()                  #forgot to save it, now to save it
>>> entry2.save()
>>> entry3.save()
>>> e=Entry.objects.all()
>>> e                                    #save successfully
<QuerySet [<Entry: entry1>, <Entry: entry2>, <Entry: entry3>]>
>>> blog=Blog(name='blog1',entry='entry1')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "Z:\xxxxxx\base.py", line 477, in __init__
    _setattr(self, field.name, rel_obj)
  File "Z:\xxxxxx\related_descriptors.py", line 197, in __set__
    self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "'entry1'": "Blog.entry" must be a "Entry" instance.          #must be a instance of Entry, not the entry's name
>>> blog=Blog(name='blog1',entry=entry1)                   #create successfully
>>> blog
<Blog: blog1>
>>> blog.entry
<Entry: entry1>
>>> blog.save() #don't forget to save it
从多里面查一。
>>> dir(blog)
[..., 'entry', 'entry_id', 'id', 'name', 'objects',... ]
#we can find both 'entry' and 'entry_id', then we can find the entry_id through blog
>>> a=blog.entry_id
>>> a
1
>>> b=blog.entry
>>> b
<Entry: entry1>           #object
>>>

从一里面查多。

>>> dir(entry1)
[ 'blog_set', 'check', 'id', 'name', 'objects'...]
#we can find related blog sets through blog_set
>>> c=entry1.blog_set
>>> c
<django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager object at 0x0000000003EDEF60>
>>> d=entry1.blog_set.all()

    >>> entry1.blog_set.all()
   <QuerySet [<Blog: blog1>]>

  

  

2.manytomany

3.onetoone

posted on 2018-05-08 23:51  mingxiazhichan  阅读(167)  评论(0编辑  收藏  举报

导航