1

This is my models.py

class Product(models.Model):
    product = ArrayField(ArrayField(models.CharField(max_length=200), blank=True))
 def __str__(self):
         return self.product

But i'm getting error like :

TypeError at /admin/ordering/product/add/ str returned non-string (type list)

Anish
  • 4,262
  • 6
  • 36
  • 58
neha
  • 25
  • 7
  • you need to convert it to string to display – webbyfox Mar 27 '19 at 11:33
  • https://stackoverflow.com/questions/5618878/how-to-convert-list-to-string – Endre Both Mar 27 '19 at 11:35
  • method __str__ should return string, not list. – Anish Mar 27 '19 at 11:37
  • Actually im new to django i just searched how to use arary field in django model and i got this https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/fields/ – neha Mar 27 '19 at 11:37
  • Possible duplicate of [How to convert list to string](https://stackoverflow.com/questions/5618878/how-to-convert-list-to-string) – webbyfox Mar 27 '19 at 11:37
  • Actually i want to take the products as array so i have used arrary field but im not getting how to return it as an array instead of str – neha Mar 27 '19 at 11:40
  • First of all welcome to stackoverflow and congratulations for posting a good first question. you need to manually convert your list to string simplest way could be to use `return str(self.product)` – sid-m Mar 27 '19 at 11:40

2 Answers2

0

In your __str__() method of model Product self.product returns list of names.

class Product(models.Model):
    ...
    def __str__(self):
         return self.product  # This returns list of names 

You can either convert self.product to string manually or replace with following one.

class Product(models.Model):
    ...
    def __str__(self):
         return ", ".join(self.product)  # This would join list of names with ,
Devang Padhiyar
  • 3,427
  • 2
  • 22
  • 42
0

Just convert your product array to string. For that you can type cast product array to string

class Product(models.Model):
    product = ArrayField(ArrayField(models.CharField(max_length=200), blank=True))
 def __str__(self):
         return str(self.product)

str(anything) will convert any python object into its string representation

Anish
  • 4,262
  • 6
  • 36
  • 58