>> 此文档长期更新,想到哪里写到哪里
Django高级用法
模型多对多关系
在建立多对多的模型时,如果需要在关系中添加额外的字段,常用的做法是通过建立第三张表,分别外键关联到对应的两张表上。
但是此种方法在使用时 prefetch_related 提供的便捷关联查询就无法快速使用。可以通过使用 [through] 来完成
根据指定条件获取当前模型数据的最后一条
原来使用 User.objects.all().order_by('-create_time').first()
可以通过在模型Meta中指定
get_latest_by = ['-priority', 'order_date']
项目开发中的经验
创建包含树形结构的模型
> 这是普通的模型,如果我们在进行树形结构查询时,基本上只能通过 递归查询,或者分层查询。但是当前查询方式还是并非最佳实践
class Department(BaseModel):
name = models.CharField("名称", max_length=200)
nick_name = models.CharField("别名", max_length=200, blank=True, null=True)
full_name = models.CharField("全称", max_length=200, blank=True, null=True)
parent_id = models.IntegerField("父级对象", blank=True, null=True)
> 我们在创建树形数据对象时,除了维护 parent 信息之外,可以加入额外的字段表示当前对象所处的位置
参考文档 https://blog.csdn.net/u013007900/article/details/78093563
class TreeTest(MPTTModel):
name = models.CharField("TEST", max_length=1024)
parent = TreeForeignKey("self", blank=True, null=True, related_name="children", on_delete=models.DO_NOTHING)
https://django-mptt.readthedocs.io/en/latest/models.html
def test_tree(self, request, *args, **kwargs):
res = {}
instance = TreeTest.objects.get(pk=7)
# 返回一个包含所有当前实例祖宗的queryset
ancetors = instance.get_ancestors(ascending=False, include_self=False)
res["ancetors"] = [i.name for i in ancetors]
# 返回包换当前实例的直接孩子的queryset(即下一级所有的子节点),按树序排列
children = instance.get_children()
res["children"] = [i.name for i in children]
# 返回当前实例的所有子节点,按树序排列
descendants = instance.get_descendants(include_self=False)
res["descendants"] = [i.name for i in descendants]
family = instance.get_family()
res["family"] = [i.name for i in family]
return Response(res)
树形结构的查询,基本上都是在一次SQL下完成的
获取django项目中的所有的url
https://blog.csdn.net/qq_41572228/article/details/112184600