Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use __str__ with foreign key '__str__ returned non-string (type Product)'

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 !

like image 619
namo Avatar asked Jan 01 '23 16:01

namo


1 Answers

You can not return something other than a string from the __str__ method. self.product is not a string, 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)
like image 131
Willem Van Onsem Avatar answered Jan 04 '23 23:01

Willem Van Onsem