django页面枚举转换显示

本文介绍了在Django中如何设置页面默认显示的值,特别是针对枚举类型的处理。讨论了两种方法:当枚举数量确定时直接在model中定义并展示,以及当枚举值需要从数据库查询时的处理方式。同时提到了Django2.0以后外键关联的on_delete约束。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:枚举数量确定的枚举值显示

  1. 创建枚举
 TOTAL_STATUS = (
    (0, "初始化"),
    (10, "清关中"),
    (20, "已清关"),
    (25, "取消中"),
    (30, "已取消"),
)
  1. model 中特定的值使用枚举:
 status = models.PositiveIntegerField(blank=True, null=True, choices=SALEORDER_STATUS_ENUM)
  1. 前端使用方式
 <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>

附录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值