1. 程式人生 > 其它 >django queryset用法總結二

django queryset用法總結二

1、動態條件查詢

簡單: design_list = Design.objects.filter(Q(tags__tag__contains = "tag1") and Q(tags__tag__contains = "tag2")
條件特別多,數量不定,動態的怎麼辦?
tag_list = ['tag1', 'tag2', 'tag3']
base_qs = Design.objects.all()
for t in tag_list:
    base_qs = base_qs.filter(tags__tag__contains=t)

以上,其實是 and條件, .filter( Q () & Q() )

想用or 要這樣寫:

tags = ['tag1', 'tag2', 'tag3']
q_objects = Q() # Create an empty Q object to start with
for t in tags:
    q_objects |= Q(tags__tag__contains=t) # 'or' the Q objects together

designs = Design.objects.filter(q_objects)
    tags = ['tag1', 'tag2', 'tag3']
    q_objects = Q()  # Create an empty Q object to start with
for t in tags: q_objects |= Q(name=t) # 'or' the Q objects together print(str(Student.objects.values('name').filter(q_objects).query))

輸出:SELECT "d3_student"."name" FROM "d3_student" WHERE ("d3_student"."name" = tag1 OR "d3_student"."name" = tag2 OR "d3_student"."name" = tag3)

除了 |=

還有 &= 看如下例子

   q_objects = Q()
          for f in self.get_form_fields():
              if self.form.cleaned_data.get(f):
                  q_objects &= Q(**{f+'__icontains':self.form.cleaned_data[f]})

2、group by (annotate, aggregate)

(1) aggregate後,變為dict,不是queryset

>>> from django.db.models import Avg, Max, Min, Sum, Count
>>> User.objects.all().aggregate(Avg('id'))
{'id__avg': 7.571428571428571}
>>> User.objects.all().aggregate(Max('id'))
{'id__max': 15}
>>> User.objects.all().aggregate(Min('id'))
{'id__min': 1}
>>> User.objects.all().aggregate(Sum('id'))
{'id__sum': 106}

(2)annotate是增加新的一列,結果仍是queryset

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    name = models.CharField(max_length=300)
    rating = models.FloatField()
    authors = models.ManyToManyField(Author)

Author.objects.values('name').annotate(average_rating=Avg('book__rating'))

上面例子, 相當於最傳統的guoup :select auther.name, Avg(book.rating) from auther, book where auther.id=book.author_id group by auther.name

會合並相同的name,計算rating的平均值。 group by 一定是被查詢欄位的非計算列

3、如何確保table只有一行資料

class Origin(models.Model):
    name = models.CharField(max_length=100)

    def save(self, *args, **kwargs):
        if self.__class__.objects.count():
            self.pk = self.__class__.objects.first().pk
        super().save(*args, **kwargs)

PK設定相同的值,就不會add,而是update .

如何複製或者克隆一行資料

In [2]: Hero.objects.all().count()
Out[2]: 4

In [3]: hero = Hero.objects.first()

In [4]: hero.pk = None

In [5]: hero.save()

In [6]: Hero.objects.all().count()
Out[6]: 5

4、insert一個table時候,自動更新其他table

class Category(models.Model):
    name = models.CharField(max_length=100)
    hero_count = models.PositiveIntegerField()
    villain_count = models.PositiveIntegerField()
    class Meta:
        verbose_name_plural = "Categories"

class Hero(models.Model):
    name = models.CharField(max_length=100)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

class Villain(models.Model):
    name = models.CharField(max_length=100)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

自動更新舉例:

class Hero(models.Model):

    def save(self, *args, **kwargs):
        if not self.pk:
            Category.objects.filter(pk=self.category_id).update(hero_count=F('hero_count')+1)
        super().save(*args, **kwargs)

class Villain(models.Model):

    def save(self, *args, **kwargs):
        if not self.pk:
            Category.objects.filter(pk=self.category_id).update(villain_count=F('villain_count')+1)
        super().save(*args, **kwargs)

注意: 直接self.category.hero_count+=1 這樣寫的話,update操作也會+1

如果用signal,相同邏輯可以這樣寫:

from django.db.models.signals import pre_save
from django.dispatch import receiver

@receiver(pre_save, sender=Hero, dispatch_uid="update_hero_count")
def update_hero_count(sender, **kwargs):
    hero = kwargs['instance']
    if hero.pk:
        Category.objects.filter(pk=hero.category_id).update(hero_count=F('hero_count')+1)

@receiver(pre_save, sender=Villain, dispatch_uid="update_villain_count")
def update_villain_count(sender, **kwargs):
    villain = kwargs['instance']
    if villain.pk:
        Category.objects.filter(pk=villain.category_id).update(villain_count=F('villain_count')+1)

那麼, 使 擴充套件save()還是用signal呢? 建議擴充套件save(), 簡單好理解。 但是如果涉及第三方app更新這個table,就只能用signal了

5、擴充套件定製truncate

普通刪除可以

>>> Category.objects.all().count()
7
>>> Category.objects.all().delete()
(7, {'entity.Category': 7})
>>> Category.objects.all().count()
0

以上就是DELETEFROM... , 但是如果是海量資料表,就會很慢,可以用如下方法

class Category(models.Model):
    # ...

    @classmethod
    def truncate(cls):
        with connection.cursor() as cursor:
            cursor.execute('TRUNCATE TABLE "{0}" CASCADE'.format(cls._meta.db_table))

可以Category.truncate()來刪除資料。

6、How to convert string to datetime and store in database

日期字串不能直接儲存在date field欄位,可以這樣做

>>> user = User.objects.get(id=1)
>>> date_str = "2018-03-11"
>>> from django.utils.dateparse import parse_date // Way 1
>>> temp_date = parse_date(date_str)
>>> a1 = Article(headline="String converted to date", pub_date=temp_date, reporter=user)
>>> a1.save()
>>> a1.pub_date
datetime.date(2018, 3, 11)
>>> from datetime import datetime // Way 2
>>> temp_date = datetime.strptime(date_str, "%Y-%m-%d").date()
>>> a2 = Article(headline="String converted to date way 2", pub_date=temp_date, reporter=user)
>>> a2.save()
>>> a2.pub_date
datetime.date(2018, 3, 11)

1、

1、

1、