0

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.

2
  • Can you show some sample JSON object(s)? Commented Jul 4, 2018 at 17:49
  • @Willem Van Onsem, you mean data examle from example.json ? Commented Jul 4, 2018 at 17:53

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.