Answer the question
In order to leave comments, you need to log in
How to display an inlines relationship in a template?
There are two models, they are connected by a foreign key, they are displayed connected in the admin panel using inlines
How to output to the template in the same way as in the admin
panel models.py
class Order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, default = None, verbose_name='Пользователь')
total_price = models.DecimalField(max_digits=10, decimal_places=2, default = 0, verbose_name='Сумма заказа')
created = models.DateTimeField(auto_now_add=True, verbose_name='Дата добовления')
status = models.ForeignKey(Status, on_delete=models.CASCADE, verbose_name='Статус')
order = models.ForeignKey(Order, blank=True, on_delete=models.CASCADE, null=True, verbose_name='Заказ')
def __str__(self):
return "Заказ %s %s" % (self.id, self.status.name)
class Meta:
verbose_name = 'Заказ'
verbose_name_plural = 'Заказы'
def save(self, *args, **kwargs):
super(Order, self).save(*args, **kwargs)
class ProductsInOrder(models.Model):
order = models.ForeignKey(Order, blank=True, on_delete=models.CASCADE, null=True, verbose_name='Заказ')
created = models.DateTimeField(auto_now_add=True, verbose_name='Дата добовления')
product = models.ForeignKey(Product, blank=True, on_delete=models.CASCADE, null=True, verbose_name='Товар')
price_per_item = models.IntegerField(default = 1, verbose_name='Цена за одну штуку')
quantity_nbr = models.IntegerField(default = 1, verbose_name='Количество')
total_price = models.DecimalField(max_digits=10, decimal_places=2, default = 0, verbose_name='Общая сумма')
is_active = models.BooleanField(default=True, verbose_name='Состояние')
def __str__(self):
return self.product.name
class Meta:
verbose_name = 'Товар в заказе'
verbose_name_plural = 'Товары в заказе'
def save(self, *args, **kwargs):
price_per_item = self.product.price
self.price_per_item = price_per_item
print (self.quantity_nbr)
self.total_price = int(self.quantity_nbr) * price_per_item
super(ProductsInOrder, self).save(*args, **kwargs)
class ProductsInOrder(admin.TabularInline):
model = ProductsInOrder
extra = 0
can_delete = False
max_num = 0
readonly_fields = ('order', 'product', 'price_per_item', 'quantity_nbr', 'total_price', 'created')
@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
list_display = ('id', 'user', 'total_price', 'status', 'created')
readonly_fields = ('user','total_price', 'created')
inlines = [
ProductsInOrder,
]
Answer the question
In order to leave comments, you need to log in
order = models.ForeignKey(Order, blank=True, on_delete=models.CASCADE, null=True, verbose_name='Заказ')
Order.products_in_order.all()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question