[Django]-Django ValueError: Field 'id' expected a number but got 'S'

6👍

When querying a ForeignKey field, you ‘normally’ pass an instance of the model. For example:

# Example models
class AnotherModel(models.Model):
    name = models.CharField(...)


class MyModel(models.Model):
    another_model = models.ForeignKey(AnotherModel,...)


# Get the instance
another_model_instance = AnotherModel.objects.get(id=1)
# Use the instance in the query
my_model = MyModel.objects.get(another_model=another_model_instance)

You can however, use __ (double underscore) to ‘hop’ across and query a specific field. For example:

my_model = MyModel.objects.get(another_model__name='Some name')

With the above example, we are querying using the name field on the AnotherModel model. We can use this to fix the query in your view.

# Taken from your payment_complete view
for item in order_items:
    if item.item.is_footwear:
        st = StockQuantity.objects.get(
            item=item.item,
            color__item_color=item.color,
            footwear_size__footwear_size=str(item.footwear_size)
        )
    else:
        st = StockQuantity.objects.get(
            item=item.item,
            color__item_color=item.color,
            cloth_size__cloth_size=str(item.cloth_size)
        )    

Further reading: https://docs.djangoproject.com/en/3.1/topics/db/queries/.

👤Karl

2👍

For footwear_size and cloth_size you are sending the actual value to the view (S, M, L, etc), but your field is a foreign key, which is an integer.

You need to either pass the foreign key value instead of the string value, or change your lookup to search for the string value (something like footwear_size__name=str(item.footwear_size)).

Leave a comment