How to populate Postgresql DB via existing Django models

I have the following models in my Django application -

Class PurchaseModel(models.Model): purchaser_name = models.CharField(…) quantity = models.IntegerField(…)

Class PurchaseStatusModel(model.Model):
purchase = models.ForeignKey(PurchaseModel) status = models.CharField(

max_length=25, choices=(

(‘open’, ‘Open’),
(‘verified, ‘Verified’), (‘dispatched’, ‘Dispatched’), (‘delivered, ‘Delivered’),
)

created_at = models.DateTimeField(auto_now_add=True)

I need to use Postgresql and write a Python script to populate the two models with:

  1. 5000 PurchaseModel entries with purchaser_name randomly chosen from 10 random names. Quantity can be any random number between 1 and 10 such that:
    a. Average quantity of all PurchaseModel entries is7
    b. No two purchasers will have the same average quantity

  2. Each PurchaseModel object should have at most 4 out of the 5 statuses from the available status choices.
    a. The created dates for the PurchaseStatusModel objects must be randomly distributed between 01st Jan 2019 05 pm IST and 31st March 2020 10 pm IST.

I am new to Django and do not have an idea of how to populate the Postgresql DB using a python script, can someone please assist me with that? This is for an internship opportunity that I am seeking. I can write the rest of the required logic on my own.

Thanks in advance!

Take a look at Writing custom django-admin commands. It’s the easiest way I know of for working with the Django ORM from a script to be run from the command line.

1 Like

Thanks Ken, will do!