开发者

Django, unique time interval for the admin panel

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 开发者_如何学Pythoncreation of a second Foo with a clashing interval won't be possible. How can this be achieved ?


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:

class FooAdmin(admin.ModelAdmin):
    form = CustomFooAdminForm

and in the form you can have something like (see custom validation in forms):

# more or less pseudo code
class CustomFooAdminForm(forms.ModelForm):

    def clean(self):
        cleaned_data = super(CustomFooAdminForm, self).clean()
        interval = cleaned_data.get("end_time") - cleaned_data.get("start_time")
        type = cleaned_data.get("type")

        q = Foo.objects.extra(select={'interval':'time_end - time_start'}
        counter = q.filter(interval=intervak, type=type).count()

        if counter > 0:
            raise forms.ValidationError("ERROR!!!!")

        # Always return the full collection of cleaned data.
        return cleaned_data

Maybe you have to transform the DateTimeFields to UNIX timestamps, before you can subtract them in SQL (UNIX_TIMESTAMP(time_end) - UNIX_TIMESTAMP (time_start) for MySQL). Or you can use DATEDIFF() 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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜