I
I
iSpeedMan2020-06-11 00:27:00
Django
iSpeedMan, 2020-06-11 00:27:00

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)


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,
    ]


5ee14f88afc87328599248.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
noremorse_ru, 2020-06-11
@iSpeedMan

order = models.ForeignKey(Order, blank=True, on_delete=models.CASCADE, null=True,  verbose_name='Заказ')

Add related_name, for example related_name='products_in_order'. Now, by calling Order, you can get all the related objects of the class ProductsInOrder (it should have been called ProductInOrder), something like this:
Order.products_in_order.all()
It remains to loop through and display the necessary data. If this is quite basic, it is still desirable to take care not to make unnecessary requests to the database, but that's another story))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question