Django 数据关系的处理

来源:互联网 发布:黎明杀机淘宝好便宜 编辑:程序博客网 时间:2024/05/21 11:35

Django 数据关系的处理:OneToMany,OneToOne,MangToMany

one-to-many 类型:

>>> e = Entry.objects.get(id=2) 
>>> e.blog # Returns the related Blog object. 
>>> e = Entry.objects.get(id=2) 
>>> e.blog = some_blog 
>>> e.save() 
>>> e = Entry.objects.get(id=2) 
>>> e.blog = None 
>>> e.save() # "UPDATE blog_entry SET blog_id = NULL ...;" 
>>> e = Entry.objects.get(id=2) 
>>> print e.blog  # Hits the database to retrieve the associated Blog. 
>>> print e.blog  # Doesn't hit the database; uses cached version. 
>>> e = Entry.objects.select_related().get(id=2) 
>>> print e.blog  # Doesn't hit the database; uses cached version. 
>>> print e.blog  # Doesn't hit the database; uses cached version 
>>> b = Blog.objects.get(id=1) 
>>> b.entry_set.all() # Returns all Entry objects related to Blog. 
# b.entry_set is a Manager that returns QuerySets. 
>>> b.entry_set.filter(headline__contains='Lennon') 
>>> b.entry_set.count() 
>>> b = Blog.objects.get(id=1) 
>>> b.entries.all() # Returns all Entry objects related to Blog. 
# b.entries is a Manager that returns QuerySets. 
>>> b.entries.filter(headline__contains='Lennon') 
>>> b.entries.count() 
You cannot access a reverse ForeignKey Manager from the class; it must be accessed from an instance: 
>>> Blog.entry_set 
add(obj1, obj2, ...) 
    Adds the specified model objects to the related object set. 
create(**kwargs) 
    Creates a new object, saves it and puts it in the related object set. Returns the newly created object. 
remove(obj1, obj2, ...) 
    Removes the specified model objects from the related object set. 
clear() 
    Removes all objects from the related object set. 
    
many-to-many类型: 
e = Entry.objects.get(id=3) 
e.authors.all() # Returns all Author objects for this Entry. 
e.authors.count() 
e.authors.filter(name__contains='John') 
a = Author.objects.get(id=5) 
a.entry_set.all() # Returns all Entry objects for this Author. 


one-to-one 类型: 
class EntryDetail(models.Model): 
    entry = models.OneToOneField(Entry) 
    details = models.TextField() 


ed = EntryDetail.objects.get(id=2) 

ed.entry # Returns the related Entry object 



使用sql语句进行查询: 


def my_custom_sql(self): 
    from django.db import connection 
    cursor = connection.cursor() 
    cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz]) 
    row = cursor.fetchone() 
    return row 

原创粉丝点击