Ести две модели, они соединены по внешнему ключу, выводятся связанными в админке с помощью inlines
Как вывести в шаблон так же как в админке
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)
admin.py
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,
]