Akaash
Akaash

Reputation: 33

Field 'id' expected a number but got (<OrderItem: 1 of Dummy 1>, True)

error message:

TypeError: Field 'id' expected a number but got (OrderItem: 1 of Dummy 1>, True).

I have to create a simple e-commerce site in Django and I am new to this so help to solve the problem guys.

views.py

def add_to_cart(request, slug):
item = get_object_or_404(Item, slug=slug)
order_item = OrderItem.objects.get_or_create(item=item)
order_qs = Order.objects.filter(user=request.user,ordered=False)
if order_qs.exists():
    order = order_qs[0]
    if order.items.filter(item__slug=item.slug).exists():
        order_item.quantity += 1
        order_item.save()
else:
    ordered_date = timezone.now()
    order = Order.objects.create(user=request.user, ordered_date=ordered_date)
    order.items.add(order_item)
return redirect("core:product", slug=slug)

models.py

This is my model view I struck with is error help me to find out what was that.

from django.db import models
from django.conf import settings 
from django.shortcuts import reverse

# Create your models here.
CATEGORY_CHOICES = (
    ('S','Shirt'),
    ('SW','Sport Wear'),
    ('OW','Outwear')
)


LABLE_CHOICES = (
    ('P','primary'),
    ('S','secondary'),
    ('D','danger')
)

class Item(models.Model):
    title = models.CharField(max_length= 100)
    price = models.FloatField()
    discount_price = models.FloatField(blank=True , null=True)
    category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
    label = models.CharField(choices=LABLE_CHOICES, max_length=1)
    slug = models.SlugField()
    description = models.TextField()

    def __str__(self):
        return self.title


    def get_absolute_url(self):
        return reverse("core:product", kwargs={
            "slug": self.slug
            })

    def get_add_to_cart_url(self):
        return reverse("core:add-to-cart", kwargs={
            "slug": self.slug
            })

class OrderItem(models.Model):
    item = models.ForeignKey(Item, on_delete= models.CASCADE)
    quantity = models.IntegerField(default=1)

    def __str__(self):
        return f"{self.quantity} of {self.item.title}"

class Order(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                            on_delete= models.CASCADE)
    items = models.ManyToManyField(OrderItem)
    start_date = models.DateTimeField(auto_now_add=True)
    ordered_date = models.DateTimeField()
    ordered = models.BooleanField(default=False)

    def __str__(self):
        return self.user.username

could you please give an idea about how to solve the problem, Thanks in advance

error file

 Traceback (most recent call last):
  File "C:\Users\Mr Akash\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\fields\__init__.py", line 1772, in get_prep_value
    return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number,
not 'tuple'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Mr Akash\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Mr Akash\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Mr Akash\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Mr Akash\desktop\project\ecommerce\core\views.py", line 37,
in add_to_cart
    order.items.add(order_item)
  File "C:\Users\Mr Akash\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\fields\related_descriptors.py", line 946, in add
    through_defaults=through_defaults,
  File "C:\Users\Mr Akash\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\fields\related_descriptors.py", line 1129, in _add_items
    ], ignore_conflicts=True)
  File "C:\Users\Mr Akash\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\query.py", line 493, in bulk_create
    objs_without_pk, fields, batch_size, ignore_conflicts=ignore_conflicts,
  File "C:\Users\Mr Akash\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\query.py", line 1230, in _batched_insert
    self._insert(item, fields=fields, using=self.db, ignore_conflicts=ignore_conflicts)
  File "C:\Users\Mr Akash\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\query.py", line 1204, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\Mr Akash\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\compiler.py", line 1390, in execute_sql
    for sql, params in self.as_sql():
  File "C:\Users\Mr Akash\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\compiler.py", line 1335, in as_sql
    for obj in self.query.objs
  File "C:\Users\Mr Akash\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\compiler.py", line 1335, in <listcomp>
    for obj in self.query.objs
  File "C:\Users\Mr Akash\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\compiler.py", line 1334, in <listcomp>
    [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  File "C:\Users\Mr Akash\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\compiler.py", line 1275, in prepare_value
    value = field.get_db_prep_save(value, connection=self.connection)
  File "C:\Users\Mr Akash\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\fields\related.py", line 939, in get_db_prep_save
    return self.target_field.get_db_prep_save(value, connection=connection)
  File "C:\Users\Mr Akash\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\fields\__init__.py", line 821, in get_db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
  File "C:\Users\Mr Akash\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\fields\__init__.py", line 2365, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Users\Mr Akash\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\fields\__init__.py", line 1776, in get_prep_value
    ) from e
TypeError: Field 'id' expected a number but got (<OrderItem: 1 of Dummy 1>, True).

Upvotes: 2

Views: 810

Answers (1)

Vinay
Vinay

Reputation: 657

As per Django's documentation, get_or_create - Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.

So if you save output to a single variable, it is a tuple. Modify your code as below

order_item, created = OrderItem.objects.get_or_create(item=item)

Upvotes: 5

Related Questions