Issue
while i try to
__str__()
method for a foreign it provide this error
__str__ returned non-string (type Product)
models.py
class Product(models.Model):
product_name = models.CharField(unique=True, max_length=50 ,
blank=False,null=False)
price = models.PositiveIntegerField()
active = models.BooleanField(default=True)
def __str__(self):
return self.product_name
class ProductOrder(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE ,
null=True)
ordering = models.ForeignKey(Order,
on_delete=models.CASCADE,blank=True,null=True)
pass
def __str__(self):
return self.product
i also tried this
def __str__(self):
return self.product.product_name
#product_name is a field from Product table
the error will provide is
__str__ returned non-string (type QuerySet)
how to represent it , thanks for reply !
Solution
You can not return something other than a str
ing from the __str__
method. self.product
is not a str
ing, but a Product
object.
You can however call str(..)
over it, to get the textual representation of that Product
:
class ProductOrder(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)
ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True)
def __str__(self):
return str(self.product)
Answered By - Willem Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.