想象一下,我有一个描述办公室打印机的模型。他们可以准备工作或不工作(可能在存储区域或已经购买但仍未在办公室......)。该模型必须有一个字段代表打印机的phisicaly位置(“秘书办公室”,“接待”,......)。不能有两个重复的位置,如果它不起作用,它就不应该有位置。
我想要一个列表,其中显示所有打印机,并且每个打印机都有一个位置(如果有)。像这样:
ID | Location
1 | "Secretary's office"
2 |
3 | "Reception"
4 |
有了这个,我可以知道有两台打印机在工作(1和3),其他打印机在线(2和4)。
该模型的第一种方法应该是这样的:
class Printer(models.Model):
brand = models.CharField( ...
...
location = models.CharField( max_length=100, unique=True, blank=True )
但是这不能正常工作。您只能存储一个具有一个空白位置的寄存器。它作为空字符串存储在数据库中,并且不允许您插入多次(数据库表示该字段有另一个空字符串)。如果将“null = True”参数添加到此参数,则其行为方式相同。这是不行的,而不是在相应的列中插入NULL值,默认值是一个空字符串。
在网上搜索我找到http://www.maniacmartin.com/2010/12/21/unique-nullable-charfields-django/,试图以不同的方式解决问题。他说可能最干净的是最后一个,他在其中继承CharField类并覆盖一些方法来在数据库中存储不同的值。这是代码:
from django.db import models
class NullableCharField(models.CharField):
description = "CharField that obeys null=True"
def to_python(self, value):
if isinstance(value, models.CharField):
return value
return value or ""
def get_db_prep_value(self, value):
return value or None
这很好用。您可以存储多个没有位置的寄存器,因为它不存储空字符串,而是存储NULL。问题是它显示空白位置Nones而不是空字符串。
ID | Location
1 | "Secretary's office"
2 | None
3 | "Reception"
4 | None
我认为有一个方法(或多个)必须在两种方式(数据库到模型和模型到数据库)中指定模型和数据库类管理器之间必须如何转换数据。
这是获得唯一空白CharField的最佳方式吗?
谢谢,
答案 0 :(得分:1)
答案 1 :(得分:1)
您可以使用模型方法以自定义方式输出值。
像这样(在您的模型类中):
def location_output(self):
"Returns location and replaces None values with an empty string"
if self.location:
return self.location
else:
return ""
然后你可以在这样的视图中使用它。
>>> Printer.objects.create(location="Location 1")
<Printer: Printer object>
>>> Printer.objects.create(location=None)
<Printer: Printer object>
>>> Printer.objects.get(id=1).location_output()
u'Location 1'
>>> Printer.objects.get(id=2).location_output()
''
在你的模板中,就像这样。
{{ printer.location_output }}