django 杂记

date
Apr 25, 2021
slug
32
status
Published
tags
Python
Django
summary
type
Post

related_name和related_query_name

class Author(models.Model):
    name = models.CharField(verbose_name='姓名', max_length=50)
    age = models.IntegerField(verbose_name='年龄')

class Book(models.Model):
    name = models.CharField(verbose_name='书名', max_length=100)
    author = models.ForeignKey(Author, verbose_name='作者', related_name='bs', related_query_name='b')

Author.objects.filter(b__name='learn_python')
#通过related_query_name查询书名为learn_python的作者

author = Author.objects.get(pk=1)
author.bs.all()
通过related_name来查询该作者所有的书

Django include 和 path re_path

带正则表达式的用re_path否则会有warning

re_path(r"swagger(?P<format>\.json|\.yaml)", schema_view.without_ui(cache_timeout=0), name="schema-json"),
path(r"swagger/", schema_view.with_ui("swagger", cache_timeout=0), name="schema-swagger-ui"),
path(r"redoc/", schema_view.with_ui("redoc", cache_timeout=0), name="schema-redoc"),

path 不需要开头结尾的^和$

include

include(module, namespace=None) # 或者是一个url module -- 包含urlpatterns属性的模块 
include(pattern_list) # 一个包含path 的列表 -- urlpatterns
include((pattern_list, app_namespace), namespace=None)
 

© chaleaoch 2021