P
P
Pavel Echo2021-09-29 16:43:48
Django
Pavel Echo, 2021-09-29 16:43:48

How to add many objects to database in Django TabularInLine?

I currently need to add many objects to a pass-through table using python manage.py shell.
I will describe the models here in a nutshell, I will not litter with extra fields.
So I have a Product model:

class Product(models.Model):
    name = models.CharField(max_length=200, db_index=True, unique=True)
    slug = models.SlugField(max_length=200, db_index=True, unique=True)

Next, I implemented the Shop model:
class Shop(models.Model):
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True)

I need to have a through table where I would regulate, for example, prices inside the store and balances inside the store, so I implemented the ShopQuantity model:
class ShopQuantity(models.Model):
    shop = models.ForeignKey(Shop, blank=True, on_delete=models.CASCADE, null=True, related_name='product_list')
    product = models.ForeignKey(Product, blank=True, on_delete=models.CASCADE, null=True, related_name='shop_list')
    price = models.DecimalField(max_digits=10, decimal_places=2, default='0')
    quantity = models.IntegerField(blank=True, null=True, default='0')

For clarity, I will present here what the admin panel looks like for this structure:
class ShopQuantityInline(admin.TabularInline):
    model = ShopQuantity
    extra = 0

@admin.register(Shop)
class ShopAdmin(admin.ModelAdmin):
    fields = ['name', 'slug']
    list_display = ['name']
    inlines = [ShopQuantityInline]

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    fields = ['name', 'slug']
    list_display = ['name']
    inlines = [ShopQuantityInline]

Let's say I already have 1000 items in the database. Can you please tell me how can I put these 1000 products in the Shop table. I know it's possible to use manage.py shell, but I don't understand how.
I can create 1000 objects for the store using a regular loop, but I get just empty entries (in this example, I just create 5 entries):
for i in range(5):
    p = ShopQuantity.objects.create()
    p.save()


The image shows the usual ShopQuantity pass -through table for the Shop table . Exactly what I would like:
61546d0114c5d022151176.png
and so on up to the number of products available in the database (if there are 1000, then 1000)
If anyone has encountered this and solved this problem, please help.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question