这是我正在使用的模型:
from django.db import models
from django.conf import settings
from products.models import Variation
class CartItem(models.Model):
cart = models.ForeignKey('Cart')
items = models.ForeignKey(Variation)
quantity = models.PositiveIntegerField(default=1)
def __unicode__(self):
return self.items.title
class Cart(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
items = models.ManyToManyField(Variation, through='CartItem')
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
def __unicode__(self):
return (str(self.id))
我之前运行过makemigrations
和migrate
,模型items
中的Cart
字段为items = models.ManyToManyField(CartItem)
现在进行此更改后,我收到以下错误:
ValueError: Cannot alter field carts.Cart.items into carts.Cart.items - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields)
我该如何解决这个问题?请帮忙。
答案 0 :(得分:1)
与错误一样,您无法将多对多转换为外键。您必须将其拆分为两个迁移:首先,完全删除原始字段并运行makemigrations以创建DROP COLUMN调用;然后,添加外键并再次运行makemigrations以创建ADD COLUMN。