我遇到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
将返回IntegrityError。我在datefield中添加了唯一的功能,但得到了相同的错误。
我使用Django 1.11和Python 2.7
我重置数据库几次但它没有帮助,db是Postgres / sqlite。
答案 0 :(得分:0)
unique_together
导致完整性问题。移除该行然后进行迁移。
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')