Django IntegrityError与dateField-使用get_or_create创建对象时



我遇到了Django的get_or_create,当我创建具有相同日期完整性错误的相同对象时,请弹出。

我的模型中的字段如下。

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

当我尝试以相同的日期和直至日期为购物车中添加相同的对象时,出现了错误:

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在创建具有相同日期的对象时将返回firtegityError。我在dateField中添加了唯一功能,但遇到了相同的错误。我使用Django 1.11和Python 2.7

我几次重置数据库,但没有帮助,数据库是postgres/sqlite。

unique_together在CARTLINE模型中引起完整性问题。

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:
        verbose_name = pgettext_lazy('Cart line model', 'Cart line')
        verbose_name_plural = pgettext_lazy('Cart line model', 'Cart lines')

相关内容

  • 没有找到相关文章

最新更新