IntegrityError with DateField - when creating objects with get_or_create

209 views Asked by At

I'm having an issue with Django's get_or_create, when ever I create same objects with same dates integrity error pops up.

I have field in my model as follows.

class Cart(models.Model):
    created = models.DateTimeField(
        pgettext_lazy('Cart field', 'created'), auto_now_add=True)
    last_status_change = models.DateTimeField(
        pgettext_lazy('Cart field', 'last status change'), auto_now_add=True)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, blank=True, null=True, related_name='carts',
        verbose_name=pgettext_lazy('Cart field', 'user'))
    email = models.EmailField(
        pgettext_lazy('Cart field', 'email'), blank=True, null=True)

    def add(self,hoarding, date_from, date_until):
        cart_line, created = self.lines.get_or_create(
            hoarding=hoarding,date_from=date_from,date_until=date_until)



class Meta:
        ordering = ('-last_status_change',)
        verbose_name = pgettext_lazy('Cart model', 'Cart')
        verbose_name_plural = pgettext_lazy('Cart model', 'Carts')

    def __str__(self):
        return smart_str(self.user)


class CartLine(models.Model):
    cart = models.ForeignKey(
        Cart, related_name='lines',
        verbose_name=pgettext_lazy('Cart line field', 'cart'))

    hoarding = models.ForeignKey(
        Hoarding, related_name='+',blank=True, null=True,
        verbose_name=pgettext_lazy('Cart line field', 'hoarding'))

    date_from = models.DateField(blank=True, null=True,
        verbose_name=pgettext_lazy('Cart line field', 'from'))

    date_until = models.DateField(blank=True, null=True,
        verbose_name=pgettext_lazy('Cart line field', 'until'))

    class Meta:
        unique_together = ('cart', 'date_from', 'date_until')
        verbose_name = pgettext_lazy('Cart line model', 'Cart line')
        verbose_name_plural = pgettext_lazy('Cart line model', 'Cart lines')

error arises when i try to add same objects to cart with same from-date and until-date:

IntegrityError at /hoardings/hoardings-demo-2-5/add/
UNIQUE constraint failed: cart_cartline.cart_id, cart_cartline.date_from, cart_cartline.date_until

get_or_create will return an IntegrityError when creating objects with same dates.I added unique features in datefield but got the same error. I use Django 1.11 and Python 2.7

I reset database few times but it doesn`t help, db is Postgres/sqlite.

1

There are 1 answers

0
zaidfazil On BEST ANSWER

The unique_together constraint is causing the error. Remove the same and all will be well.