[英]model linked with model through M2O relation which is further linked with model through M2O relation raises error
I am working on an online-shop in django.我正在 django 的网上商店工作。
I have linked the order
model with the cart
model through ForeignKey
which is further linked with products
model through ForeignKey
.我已通过
ForeignKey
将order
model 与cart
model 相关联,并通过ForeignKey
进一步与products
model 相关联。
models.py
: models.py
:
class products(models.Model):
image = models.ImageField(upload_to='products/')
name = models.CharField(max_length=50)
slug = models.SlugField(blank=True, unique=True)
title = models.CharField(max_length=50)
price = models.FloatField()
def __str__(self):
return self.name
class cart(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
item = models.ForeignKey(products, on_delete=models.CASCADE) ###
slug = models.CharField(max_length=50, default='#')
quantity = models.IntegerField(default=1)
created_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'{self.quantity} of {self.item.name}'
def get_total(self):
total = self.item.price * self.quantity
floattotal = float("{0:.2f}".format(total))
return floattotal
class order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
item = models.ForeignKey(cart, on_delete=models.CASCADE) ###
slug = models.SlugField()
quantity = models.IntegerField()
created_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'{self.quantity} of {self.item.item__name}'
I wanted to create object of order as:我想创建 object 的顺序为:
def order_view(request, slug):
cart_qs = cart.objects.filter(user=request.user, slug=slug)
cart_item = cart_qs[0]
order.objects.create(user=request.user, item=cart_item.item.name, slug=slug, quantity=cart_item.quantity) ####
It raises error as:它引发错误为:
Cannot assign "'The latest one'": "order.item" must be a "cart" instance.
Why this error arises and how can I resolve this?为什么会出现此错误,我该如何解决?
You are trying to assign string on Order
instance creation where it's expecting a Cart
instance.您正在尝试在期望
Cart
实例的Order
实例创建上分配字符串。 The error raised here:这里提出的错误:
item=cart_item.item.name
It should be simply:应该很简单:
item=cart_item
, because your model schema expect this: ,因为您的 model 架构期望这样:
item = models.ForeignKey(cart, on_delete=models.CASCADE) ###
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.