环境
Python 3.7.6
Django 2.2.10
ORM 操作
模型字段
常用字段
代码演示模型
本文中的所有代码均基于演示模型,但是非使用演示模型中的所有字段。
def User(models.Model):
account = models.CharField(max_length=50, uinque=True, verbose_name='账号')
password = models.CharField(max_length=50, null=True, verbose_name='密码')
name = models.CharField(max_length=50, null=True, verbose_name='姓名')
blog = models.CharField(max_length=50, null=True, verbose_name='博客地址')
创建数据
方法一
user = User.objects.create(name='Shanks', blog='yudelei.com')
方法二
user = User()
user.name = 'Shanks'
user.blog = 'yudelei.com'
user.save()
查询数据
查询数据库中的数据,users代表返回多个对象,user代表返回一个对象。
# 查询所有数据
users = User.objects.all()
# 查询有且仅有一条的数据
user = User.objects.get(account='Shanks')
# 查询符合条件的数据
users = User.objects.filter(name='Shanks')
# 查询不符合条件的数据
users = User.objects.exclude(name='Shanks')
# 对查询结果进行排序
users = User.objects.all().order_by('name')
Django-admin 重写
formfield_for_dbfield
动态设置change界面默认值(也是model的默认值)
# 参考代码一:
def formfield_for_dbfield(self, db_field, **kwargs):
if not self.request.user.is_superuser and db_field.name=='meeting':
kwargs['choices'] = (
(1, '高端会议(预报名,有审核,报名或签到时调研)'),
(2, '讲座(预报名,无审核,签到时调研抽奖)'),
)
attrs = self.get_field_attrs(db_field, **kwargs)
return db_field.formfield(**dict(attrs, **kwargs))
# 参考代码二:
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.attname == 'variable':
# Change variable field's widget with selectbox!
kwargs['widget'] = forms.Select(choices=OPTION_VARIABLE_CHOICES)
return super(SiteOptionInlineAdmin, self).formfield_for_dbfield(db_field, **kwargs)
# 参考代码三:
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.attname == 'variable':
# Change variable field's widget with selectbox!
kwargs['widget'] = forms.Select(
choices=OPTION_COLOR_VARIABLE_CHOICES)
if db_field.attname == 'value':
# change value field's widget with color picker!
db_field = RGBColorField()
return super(ThemeColorsInlineAdmin, self).formfield_for_dbfield(
db_field, **kwargs)