from django.test import TestCase
# Create your tests here.
'''
https://www.v2ex.com/t/466327
如果你的 Model 定义了默认排序字段, 必须要加 order_by()
'''
import os
if __name__ == '__main__':
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hey_star.settings")
import django
django.setup()
from light.models import Light
from django.db.models import Count
# 新增归档字段查询
# 比如查询 xxxx年x月发布的所有产品
res = Light.objects.extra(
select={"update_ym": "date_format(update_time, '%%Y-%%m-%%d')"}
).values("update_ym").annotate(c=Count("id")).values("update_ym", "c").order_by("update_ym")
print(res)
Light的model 部分
class Light(models.Model):
"""
灯具
"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
item_no = models.CharField(max_length=50, unique=True, verbose_name="编号")
name = models.CharField(max_length=100, verbose_name="名称", null=True, blank=True)
fob_ningbo_USD = models.CharField(max_length=20, verbose_name="FOB宁波(USD)")
quotation_image = models.ImageField(upload_to="light/image", verbose_name="报价图片", null=True, blank=True)
desc = RichTextUploadingField(verbose_name="产品具体描述")
first_packing = models.CharField(max_length=50, verbose_name="第一包装尺寸(CM)")
gross_weight = models.CharField(max_length=50, verbose_name="毛重(KG)")
second_packing = models.CharField(max_length=50, verbose_name="第二包装尺寸(CM)")
pks_qty = models.CharField(max_length=20, verbose_name="装箱数(PCS)", help_text="第二包装需要多少个第一包装")
moq = models.CharField(max_length=20, verbose_name="MOQ(PCS)", help_text="最小起订量")
is_new = models.BooleanField(default=False, verbose_name="是否新品")
is_hot = models.BooleanField(default=False, verbose_name="是否热销")
category = models.ForeignKey(LightCategory, on_delete=models.CASCADE, verbose_name="分类")
add_time = models.DateTimeField(auto_now_add=True, verbose_name="添加时间")
update_time = models.DateTimeField(auto_now=True, verbose_name="修改时间")
class Meta:
verbose_name = "灯具"
verbose_name_plural = verbose_name
ordering = ['-add_time']
def __str__(self):
return self.item_no
def picture_img(self):
if self.quotation_image:
return mark_safe('<img src="%s" width="100px" />' % self.quotation_image.url)
else:
return '没有图片'
picture_img.short_description = '缩略图'
def delete(self, using=None, keep_parents=False):
if os.path.isfile(self.quotation_image.path):
os.remove(self.quotation_image.path)
super(Light, self).delete(using, keep_parents)
# 自定义 get_absolute_url 方法
# 记得从 django.urls 中导入 reverse 函数
def get_absolute_url(self):
# return reverse("light:light-detail", kwargs={"pk": self.pk})
# return reverse("light:thank_you")
return reverse("light:light-detail", args=[str(self.id)])