Home > database >  model relationship and Queries in Django not a clear
model relationship and Queries in Django not a clear

Time:04-17

what does these lines of code mean in Django View: i couldn't find a details explanation, I came to Django from a Laravel background, so I can understand the models and relationships... thanks

customer = request.user.customer
product = Product.objects.get(id=productId)
order, created = Order.objects.get_or_create(customer=customer, complete=False)
orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)

CodePudding user response:

customer = request.user.customer

The request object has a user, the user is the authenticated user (if no user is authenticated then the AnonymousUser object is returned instead). In this example the User model (i.e. the user table) has a field called customer and we are accessing that field.

product = Product.objects.get(id=productId)

Here we are simply querying the Product table for a specific product with the given productId. Note, Django will raise an error if two records are returned when you use the .get() method (i.e. if two rows in the Product table have the same productId.

order, created = Order.objects.get_or_create(customer=customer, complete=False)

Next we use the get_or_create() method to look up an order based off of the customer (the value of which we extracted above. If an order cannot be found we will create one instead. The value of createdwill be True if a neworder` was created or False if one already existed.

orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)

Just as above we are getting or creating an OrderItem using the order and product fields.

  • Related