无法识别外键

时间:2018-11-18 04:11:42

标签: django django-models

我已经创建了两个模型。运行makemigrations时,出现以下错误:

printDec

models.py

ERRORS:
userorders.UserCartItem: (fields.E336) The model is used as an intermediate model by 'userorders.UserCart.items', but it does not have a foreign key to 'UserCart' or 'UserService'.

有什么问题的想法吗?我已将UserCartItem上的外键定义为UserCart,但看起来好像未被识别。我应该指出,我理解当您将另一个模型标识为外键并且该外键模型位于您正在使用的模型的下面时,您必须将外键模型放在引号中,因此为什么要使用引号在这一行:

class UserCartItem(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) 
    cart = models.ForeignKey("UserCart", on_delete=models.CASCADE)  
    quantity = models.PositiveIntegerField(default=1)
    line_item_total = models.DecimalField(max_digits=10, decimal_places=2)

    def __str__(self):
        return str(self.id)


class UserCart(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) 
    items = models.ManyToManyField(UserService, through=UserCartItem)          
    items_total = models.DecimalField(max_digits=50, decimal_places=2, default=0.00)

    def __str__(self):
        return str(self.id)

谢谢!

1 个答案:

答案 0 :(得分:0)

必须添加默认值=无:

models.ForeignKey("UserCart", on_delete=models.CASCADE, default=None)