django典型的MTV模式,最近碰上一些在template上有关数值的问题,相比于之前java中用的jsp,thymleaf模板
可能有些许不同,有时方便一些
设置页面默认显示的值
- 设置默认|default:”“与|default_if_none:”” 谁更适合你?
0会被替换成“”:<td>{{ foo.remark |default:""}}</td>
只有None才会被替换: <td>{{ foo.remark |default_if_none:""}}</td>
页面显示枚举:
方法1:枚举数量确定的枚举值显示
- 创建枚举
TOTAL_STATUS = (
(0, "初始化"),
(10, "清关中"),
(20, "已清关"),
(25, "取消中"),
(30, "已取消"),
)
- model 中特定的值使用枚举:
status = models.PositiveIntegerField(blank=True, null=True, choices=SALEORDER_STATUS_ENUM)
- 前端使用方式
<td>{{ foo.get_status_display |default_if_none:""}}</td>
方法2:枚举值需要从数据库中查询显示
一般情况下需要对应的外键与数据库对应字段连接;
官方给出的说明,需要注意的是在django2.0版本中,外键关联必须加上
on_delete=models.CASCADE,否则会报错(低版本不强制要求):
class ForeignKey(to, on_delete, **options)[source]¶
A many-to-one relationship. Requires two positional arguments: the class to which the model is related and the on_delete option.
To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey('self', on_delete=models.CASCADE).
If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself:
from django.db import models
--------------------------------------------------------------------------------
class Car(models.Model):
manufacturer = models.ForeignKey(
'Manufacturer',
on_delete=models.CASCADE,
)
# ...
class Manufacturer(models.Model):
# ...
pass
当没有必然的主外键关联的时候,可以使用mixin这个方法
1. model需要使用一个参数mixin来处理
class WarehouseMixin:
@property
def warehouse(self):
return MdWarehouse.objects.get(id=self.warehouse_id)
class SaleOrder(WarehouseMixin,models.Model):
id = models.BigIntegerField(primary_key=True)
code = models.CharField(unique=True, max_length=50, blank=True, null=True)
2 在对应前端需要使用到的情况下,可以使用对应的model包含对象的具体参数表示
<td>{{ foo.warehouse.name |default_if_none:""}}</td>