J
J
Jekson2018-07-03 19:15:42
Django
Jekson, 2018-07-03 19:15:42

Django: how to create a model instance based on data received from a json file?

There is a model with existing instances in the database.

class Instagram(models.Model):
    userid = models.CharField(max_length=255, unique=True)
    username = models.CharField(max_length=50, blank=True, null=True)
    full_name = models.CharField(max_length=50, blank=True, null=True)
    avatar = models.URLField(max_length=255, blank=True, null=True)
    bio = models.CharField(max_length=255, blank=True, null=True)
    .....
    .....

There is another model, yet without copies
class InstagramDemographicsAnalitics(models.Model):
    instagram = models.ForeignKey(Instagram, related_name='demographics')
    age_group = models.CharField(max_length=10)
    gender = models.CharField(max_length=10, default='female')
    viewer_percentage = models.DecimalField(default=0, max_digits=5, decimal_places=2)

There is a Json file that you need to go over and for each object with the corresponding userid fill in the instance fields for the associated model. As a result, for each instance of the Instagram model, I get a corresponding instance of the InstagramDemographicsAnalitics model. How can I do that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2018-07-03
@deliro

Models are something static.
Although you can try to do this at runtime, namely:
1. Generate the model itself (and also make sure that it has a unique table name)
2. Generate a migration
3. Run a migration
4. Have access to it
But this is complete nonsense. And I don’t even know cases when this might be needed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question