views:

49

answers:

2

If my model for Items is:

class Item(models.Model):
    name = models.CharField(max_length=500)
    startDate = models.DateField("Start Date", unique="true")
    endDate = models.DateField("End Date")      

Each Item needs to have a unique date range. for example, if i create an Item that has a date range of June 1st to June 8th, how can I keep and Item with a date range of June 3rd to June 5th from being created (or render an error with template logic)?

PLEASE let me know if I can clarify this question better!

A: 

http://docs.djangoproject.com/en/dev/ref/models/fields/#unique-for-date

Tyler Lane
re-read the question, he wants to add a table constraint based on a range of date. unique-for-date is "enforced at the Django admin-form level but not at the database level" as written in the doc.
dzen
+3  A: 

You can not enforce this on the model level, you can however override the save method to something like this:

class Item(models.Model):
    name = models.CharField(max_length=500)
    startDate = models.DateField("Start Date", unique="true")
    endDate = models.DateField("End Date")     

    def save(self, *args, **kwargs):
        try:
            Item.objects.get(Q(startDate__range=(self.startDate,self.endDate))|Q(endDate__range=(self.sartDate,self.endDate))|Q(startDate__lt=self.startDate,endDate__gt=self.endDate))
            #raise some save error
        except Item.DoesNotExist:
            super(Item,self).save(*args,**kwargs)

edit: maybe the date range check can go easier, long time since I did it, but it shows the general concept :).

KillianDS
+1 for enforcing this in the business logic layer, where it belongs
Bryan Ross
Thanks for the quick answers! I'll have to get back to this first thing in the morning.
tomwolber
I got this to work...but I don't know what to do after I raise the validation error. Can I make the error appear in the Admin after the user tries to save?
tomwolber
I think the best way is to throw an instance of `django.db.IntegrityError`, no ValidationError, the admin will know how to handle that. Another option is to move this to the clean method instead of the save method and throw a Validation Error (again the admin should cope). Note however the model clean method is supported only from django 1.2 on.
KillianDS