Django 数据关系的处理

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 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值