We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
The Order model has no items field.
models.py
class Order(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) postal_code = models.CharField(max_length=20) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ['-created'] indexes = [ models.Index(fields=['-created']), ] def __str__(self): return f'Order {self.id}' def get_total_cost(self): return sum(item.get_cost() for item in self.items.all())
get_total_cost() references self.items but it's not defined as a field?
The text was updated successfully, but these errors were encountered:
Hi,
This is a ForeignKey field. self.items.all is referring to its child model OrderItem. There is an OrderItem model beneath:
self.items.all
OrderItem
class OrderItem(models.Model): order = models.ForeignKey(Order, related_name="items" , on_delete=models.CASCADE) product = models.ForeignKey( Product, related_name="order_items", on_delete=models.CASCADE ) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): return str(self.id) def get_cost(self): return self.price * self.quantity
The OrderItem is the child of the model Order. In Django, the default way is to access the child model this way:
Order
self.orderitem_set.all()
As the related_name is set to items, we can access the child model using the given syntax.
related_name
items
class OrderItem(models.Model): order = models.ForeignKey(Order, related_name="items" , on_delete=models.CASCADE)
Sorry, something went wrong.
No branches or pull requests
The Order model has no items field.
models.py
get_total_cost() references self.items but it's not defined as a field?
The text was updated successfully, but these errors were encountered: