ORM for Multiple relational databases in Django

Let say that I have 3 models in an App and I need to get the price of the item using the Order Class. How can I achieve such a function? Also, since the OrderItem has Many-to-Many fields, I would like to seek help on how to loop from all the items and get the price.

Models.py

class Item(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    price = models.FloatField()


class OrderItem(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                            on_delete=models.CASCADE)
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)
    ordered = models.BooleanField(default=False)

class Order(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    items = models.ManyToManyField(OrderItem)
    start_date = models.DateTimeField(auto_now_add=True)
    ordered_date = models.DateTimeField(auto_now_add=True)
    ordered = models.BooleanField(default=False)
    total_price = models.FloatField(null=True, blank=True)

Views.py

def get_price(request):
    order = Order.objects.get(user=request.user, ordered=False)
    print(order.items.price)

When I tried to print the function get_price, It does not show anything.

Answer

Since items is ManyToManyField, you have to do:

for order_item in order.items.all():
    print(order_item.item.price)
def get_price(request):
    order = Order.objects.get(user=request.user, ordered=False)

    for order_item in order.items.all():
        print(order_item.item.price)

Leave a Reply

Your email address will not be published. Required fields are marked *