Django 模型中字段的默认值
假设我有一个模型:
class SomeModel(models.Model):
id = models.AutoField(primary_key=True)
a = models.IntegerField(max_length=10)
b = models.CharField(max_length=7)
目前我正在使用默认管理员来创建/编辑这种类型的对象。如何将字段“a”设置为与 id 具有相同的数字? (default=???)
其他问题
假设我有一个模型:
event_date = models.DateTimeField( null=True)
year = models.IntegerField( null=True)
month = models.CharField(max_length=50, null=True)
day = models.IntegerField( null=True)
如何将年、月、日字段默认设置为与 event_date 字段相同?
Suppose I have a model:
class SomeModel(models.Model):
id = models.AutoField(primary_key=True)
a = models.IntegerField(max_length=10)
b = models.CharField(max_length=7)
Currently I am using the default admin to create/edit objects of this type. How do I set the field 'a' to have the same number as id? (default=???)
Other question
Suppose I have a model:
event_date = models.DateTimeField( null=True)
year = models.IntegerField( null=True)
month = models.CharField(max_length=50, null=True)
day = models.IntegerField( null=True)
How can i set the year, month and day fields by default to be the same as event_date field?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以重写
save()
方法,如果此时a
仍然为空/null,则复制id
字段。你的第二个问题也是如此。You can override the
save()
method, and ifa
is still empty/null at that point, copy theid
field. Same goes for your 2nd question.它必须是存储在数据库中的字段吗? (冗余是不好的 yaddayadda)
如果你只想从 python 内部调用它,请使用:
does it HAVE to be a field stored in the database? (redundancy is bad yaddayadda)
If you just want to call it from inside python, use this: