ORM - Special Usages

2018-07-26  本文已影响7人  好小葱1

select_for_update

# 所有匹配的entries都会被锁定直到此次事务结束。
with transaction.atomic():
    entries = Entry.objects.select_for_update().filter(author=request.user)

select_related

from django.db import models
 
class Province(models.Model):
    name = models.CharField(max_length=10)
    def __unicode__(self):
        return self.name
 
class City(models.Model):
    name = models.CharField(max_length=5)
    province = models.ForeignKey(Province)
    def __unicode__(self):
        return self.name

get_or_created

    obj, created = Person.objects.get_or_create(
        first_name='John',
        last_name='Lennon',
        defaults={'birthday': date(1940, 10, 9)},
    )

    if created:
        # means you have created a new person
    else:
        # person just refers to the existing one

Any keyword arguments passed to get_or_create() — except an optional one called defaults — will be used in a get() call. If an object is found, get_or_create() returns a tuple of that object and False. If multiple objects are found, get_or_create raises MultipleObjectsReturned. If an object is not found, get_or_create() will instantiate and save a new object, returning a tuple of the new object and True.

bulk_create

在Django中需要向数据库中插入多条数据(list)。使用如下方法,每次save()的时候都会访问一次数据库。导致性能问题:

    for i in resultlist:
        p = Account(name=i)
        p.save()

在django1.4以后加入了新的特性。使用django.db.models.query.QuerySet.bulk_create()批量创建对象,减少SQL查询次数。改进如下:

    querysetlist=[]
    for i in resultlist:
        querysetlist.append(Account(name=i))
    Account.objects.bulk_create(querysetlist)

values_list('', flat=True)

上一篇下一篇

猜你喜欢

热点阅读