1

I have a Model named Order that has a foreign key pointed to the current user

class Order(models.Model):
customer_name = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='customer_name',
)
order_individual_price = models.IntegerField(default=1)
order_default_price = models.IntegerField(default=1)
order_name = models.CharField(max_length=200)
order_quantity = models.IntegerField(default=1)
order_total_price = models.IntegerField(default=1)

I currently have 2 order objects from 2 different users. How would I filter the objects so that it only shows the one from a specific user?

I currently have the following code: Order.objects.filter(customer_name='chironsus')

It gives me this error: ValueError: Field 'id' expected a number but got 'chironsus'.

1 Answer 1

1

'chironsus' is not the primary key of a User, it is perhaps the username. You can filter that with:

Order.objects.filter(customer_name__username='chironsus')

Note: A ForeignKey does not store the string representation (or name) of the referenced object in the column, it stores the primary key of the record it references in a column with an _id suffix to a ForeignKey field. Therefore ForeignKeys usually do not end with a _name suffix. You might want to consider renaming the customer_name field to customer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.