So, I have two models, Order
and Orders
, and for each item that I have in my session(cart)
Im creating an Order_object(saving in database) and after each item is saved I want to do a check for every Order
telling which ones are not a foreign key in Orders
, if not, create an Orders_object than add each Order
who is not a foreign key of Orders
And I wish that each Orders
have multiple Order
Models.py
class Order(models.Model):
----fields---
class Orders(models.Model):
order = models.ManyToManyField(Order)
----other fields ------
I want to dosomething like this but I dont know if it will work, can somebody confirm if this works?:
Note: even if this code that I wish to test works, im not adding multiple Order_object in Orders_object, im just creating an Orders_object containing only one Order_object, how do I fix it
for order_object in Order:
check_if_doesnt_have_foreign_key = True
for orders in Orders:
if orders.order == order_object
check_if_doesnt_have_foreign_key = False
break:
if check_if_doesnt_have_foreign_key == True:
orders = Orders(order=order_object)
orders.save()
CodePudding user response:
You could do something like that :
order = get_object_or_404(Order, pk=pk)
for order_object in Order:
if order_object.orders.exists():
# Do something
else:
# Do something
CodePudding user response:
order_all = Order.objects.all()
orders_all = Orders.objects.all()
for order_object in order_all:
the_order_object_is_not_fk_in_orders = True
for orders in orders_all:
for orders_order_object in orders.order.all():
if orders_order_object == order_object:
the_order_object_is_not_fk_in_orders = False
break
if the_order_object_is_not_fk_in_orders == True:
#do something