I'm creating a small web application to track my orders, i have two models:
Order(models.Model) " This model to record the new orders"
class Order(models.Model):
customer= models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL)
product= models.ForeignKey(Product, null=True, on_delete= models.SET_NULL)
date_created = models.DateTimeField(auto_now_add=True, null=True)
status = models.CharField(max_length=200, null=True, choices=CATEGOTRIES)
note = models.CharField(max_length=200, null=True)
OrderHistory(models.Model) " This model to record the changes for each order in any field"
class OrderHistory(models.Model):
version_num = models.AutoField(primary_key=True)
Order = models.ForeignKey(Order, null=True, on_delete= models.SET_NULL)
customer= models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL)
product= models.ForeignKey(Product, null=True, on_delete= models.SET_NULL)
date_created = models.DateTimeField(auto_now_add=True, null=True)
status = models.CharField(max_length=200, null=True)
note = models.CharField(max_length=200, null=True)
View:
def update_orders(request,pk):
theOrder = Order.objects.get(id=pk)
theHistory = createOrderHistory({
'Order': theOrder.id,
'customer': theOrder.customer,
'product': theOrder.product,
'date_created': theOrder.date_created,
'status': theOrder.status,
'note': theOrder.note
})
print('The History of the order ',theHistory)
UpdateForm = createOrder(instance=theOrder)
theid = pk
if request.method == 'POST':
UpdateForm = createOrder(request.POST,instance=theOrder)
if theHistory.is_valid():
if UpdateForm.is_valid():
theHistory.save()
UpdateForm.save()
return redirect('home')
else:
UpdateForm = createOrder(instance=theOrder)
context = {'UpdateForm':UpdateForm}
return render(request,'accounts/updateOrder.html',context)
In the View update_orders
function am taking the current order and save it into OrderHistory
and
then i save the new changes into Order
Model
it's working fine but the OrderHistory Model is not including the new change.
orderHistory
to get the history of the order
def orderHistory(request,pk):
theHistoryOfTheOrder = Order.objects.filter(id=pk).prefetch_related('Order')
#theHistoryOfTheOrder = Order.objects.filter(id=pk)
print('the query result is :',theHistoryOfTheOrder)
context = {'theHistoryOfTheOrder':theHistoryOfTheOrder}
return render(request,'accounts/orderHistory.html',context)
i tried to use prefetch_related()
since i'm fetching multiple records but it's through an error
Cannot find 'Order' on Order object, 'Order' is an invalid parameter to prefetch_related()
i need to get all the records in Order and OrderHistory with the same orderID also is this the right solution to preform History or is there another good way to do it?