vitalik / django-ninja

💨 Fast, Async-ready, Openapi, type hints based framework for building APIs
https://django-ninja.dev
MIT License
6.9k stars 418 forks source link

too many values to unpack (expected 2) #1241

Closed residentcode closed 1 month ago

residentcode commented 1 month ago

is there anything wrong ?

class Category(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique=True, blank=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        return super().save(*args, **kwargs)

    def __str__(self):
        return self.name

class Product(models.Model):
    category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE)
    title = models.CharField(max_length=255)
    tag = models.CharField(max_length=255, null=True, blank=True)
    slug = models.SlugField(max_length=255, unique=True, blank=True)
    description = models.TextField(max_length=1500, null=True, blank=True,
                                   help_text=gettext_lazy('Product description'))
    price = models.DecimalField(max_digits=6, decimal_places=2)
    discount = models.DecimalField(max_digits=6, decimal_places=2, default=0)
    in_stock = models.BooleanField(default=True)

    def __str__(self):
        return self.title
class CategorySchema(Schema):
    id: int
    title: str
    slug: str

@api.get("/category", response=List[CategorySchema])
def list_category(request):
    categories = Category.objects.all()
    return categories

class ProductSchema(Schema):
    id: int
    category: CategorySchema = None
    title: str
    slug: str
    description: str | None
    price: float
    discount: float
    in_stock: bool

@api.get("/product", response=list[ProductSchema])
def list_product(request):
    product = Product.objects.all()
    return product
rubbieKelvin commented 1 month ago

Show the error traceback

residentcode commented 1 month ago
Environment:

Request Method: GET
Request URL: http://localhost:8000/api/v1/product/

Django Version: 5.0.7
Python Version: 3.12.0
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'product']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
  File "D:\djangoninja\.venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "D:\djangoninja\.venv\Lib\site-packages\django\utils\deprecation.py", line 136, in __call__
    response = self.process_response(request, response)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\djangoninja\.venv\Lib\site-packages\django\middleware\clickjacking.py", line 27, in process_response
    if response.get("X-Frame-Options") is not None:
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\djangoninja\.venv\Lib\site-packages\django\db\models\query.py", line 635, in get
    clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
                                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\djangoninja\.venv\Lib\site-packages\django\db\models\query.py", line 1476, in filter
    return self._filter_or_exclude(False, args, kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\djangoninja\.venv\Lib\site-packages\django\db\models\query.py", line 1494, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, args, kwargs)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\djangoninja\.venv\Lib\site-packages\django\db\models\query.py", line 1501, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\djangoninja\.venv\Lib\site-packages\django\db\models\sql\query.py", line 1613, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\djangoninja\.venv\Lib\site-packages\django\db\models\sql\query.py", line 1645, in _add_q
    child_clause, needed_inner = self.build_filter(

  File "D:\djangoninja\.venv\Lib\site-packages\django\db\models\sql\query.py", line 1492, in build_filter
    arg, value = filter_expr
    ^^^^^^^^^^

Exception Type: ValueError at /api/v1/product/
Exception Value: too many values to unpack (expected 2)
fazeelghafoor commented 1 month ago

@residentcode I've tried replicating the error show in the traceback you have shared but I was not able to reproduce it. Instead I got another error which was resolved by removing title field in CategorySchema as this was not defined in the Category model and the api endpoint /api/product/ returns the correct and expected respone.

residentcode commented 1 month ago

@fazeelghafoor Thanks for your answer, I tried that but same error. which django and python ver are you using?

fazeelghafoor commented 1 month ago

@residentcode I am using Django==5.0.7 and Python==3.11.7. Going through the sample code you have provided, I have noticed that you have named model Product same as your app name. It is also mentioned in the following link that this causes some issue sometimes in Pycharm. I wonder if you create a new app with different name, do you encounter the same error?

residentcode commented 1 month ago

@fazeelghafoor I tried VS CODE and python 3.11 , whatever i do it is the same error "too many values to unpack (expected 2)", very weird.

residentcode commented 1 month ago

even simple function doesn't work, I think something wrong with clickjacking.py

@api.get('/test')
def get_text(request):
    return "Hello world"

AttributeError at /api/v1/test/ 'str' object has no attribute 'get' Request Method: GET Request URL: http://localhost:8000/api/v1/test/ Django Version: 5.0.7 Exception Type: AttributeError Exception Value:
'str' object has no attribute 'get' Exception Location: d:\pythonProject\djangoninja.venv11\Lib\site-packages\django\middleware\clickjacking.py, line 27, in process_response Raised during: product.views.get_text Python Executable: d:\pythonProject\djangoninja.venv11\Scripts\python.exe Python Version: 3.11.4

residentcode commented 1 month ago

My mistake Sorry I just included a different api.urls, solved.