Jekson
Jekson

Reputation: 3262

Django: how to create an instance of the model based on the data from the json file?

In the project 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, so far without instaces

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)

It is necessary from the file statistic.json, which is in the same folder with the project, to take the data for the corresponding userid and on their basis create the instances of the model InstagramDemographicsAnalitics.

I have no idea how to do this. I really need advice with a sequence of actions and if possible code example.

Upvotes: 0

Views: 76

Answers (1)

C14L
C14L

Reputation: 12548

As an example, this function would take an instance of Instagram and return an instance of InstagramDemographicsAnalitics:

def get_ida_instance(instagram):
    # Load all users from JSON file
    all_users = json.load('example.json')

    # Find the one user, this depends on the format of your JSON file
    my_user = [x for x in all_users if x['userid'] == instagram.userid][0]

    # Map the JSON fields to your Model
    ida = InstagramDemographicsAnalitics()
    ida.instagram = instagram
    ida.age_group = my_user['age_group']
    ida.gender = my_user['gender']
    ida.viewer_percentage = float(str(my_user['viewer_percentage']))
    ida.save()  # If you want to persist it to the database

    # Return the instance
    return ida

It depends of course on the actual format of your JSON file.

Upvotes: 1

Related Questions