views:

59

answers:

1

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 ?

+2  A: 

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).

Felix Kling
Thanks alot for the detailed explanation! For the last part (tim difference), I guess timedelta can be useful instead of unix time tricks (but not sure :) ).
Hellnar