Django,管理面板的唯一时间间隔
问候, 假设我有这样的模型:
class Foo(models.Model):
type = models.ForeignKey(Type)
start_time = models.DateTimeField()
end_time models.DateTimeField()
对于具有相同类型的每个 Foo 对象,我需要这个时间间隔(end_time - start_time)是唯一的,以便不可能创建具有冲突间隔的第二个 Foo。如何才能实现这一目标?
Greetings,
Assume I have such model:
class Foo(models.Model):
type = models.ForeignKey(Type)
start_time = models.DateTimeField()
end_time models.DateTimeField()
For each Foo object that is having the same type, I need this time interval (end_time - start_time) to be unique so that creation of a second Foo with a clashing interval won't be possible. How can this be achieved ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请参阅有关 自定义 的文档管理界面中的验证。
基本上,您必须创建自己的(模型)表单,例如
CustomFooAdminForm
并将其分配给管理模型:在表单中您可以拥有类似的内容(请参阅表单中的自定义验证):
也许您必须转换
DateTimeField
转换为 UNIX 时间戳,然后才能在 SQL 中减去它们(UNIX_TIMESTAMP(time_end) - UNIX_TIMESTAMP (time_start)
for MySQL)。或者您可以使用DATEDIFF MySQL 中的 ()
来获取差异。但请注意,如果您使用此类特殊函数(只要它们在同名的其他数据库中不可用),则将您的应用程序绑定到某个数据库。See the documentation about custom validation in the admin interface.
Basically you have to create your own (model) form, lets say
CustomFooAdminForm
and assign it to the admin model:and in the form you can have something like (see custom validation in forms):
Maybe you have to transform the
DateTimeField
s to UNIX timestamps, before you can subtract them in SQL (UNIX_TIMESTAMP(time_end) - UNIX_TIMESTAMP (time_start)
for MySQL). Or you can useDATEDIFF()
in MySQL to get the difference. But note that you tie your application to a certain database if you use such special functions (as long as they are not available in other databases under the same name).