Ahmad Javed
Ahmad Javed

Reputation: 612

How to insert values in two different database tables simultaneously in django?

I have two models classes in Django. I want to insert values in the models simultaneously using a CSV file.

Two models are User and User_Stats. User_stats has a foreign key from User. I want to insert some rows from the .csv file to User and some to User_stats. I am not sure how this will be done.

class User(models.Model):
    full_name = models.CharField('Full Name',max_length=100)
    username = models.CharField('Username',max_length=100,unique=True)
    photo = models.ImageField(upload_to = 'photos/%Y/%m/%d/',blank=True)
    email_id = models.EmailField('Email Id',blank=True)

class User_Statistics(models.Model):
    username = models.ForeignKey(User,on_delete=models.CASCADE)
    total_posts = models.PositiveIntegerField('Total Posts')
    followers = models.PositiveIntegerField('Followers')
    following = models.PositiveIntegerField('Following')
def write_to_db(file):
    with open(str(file),encoding='utf-8') as csvfile:
            csvreader = csv.reader(csvfile)
            next(csvreader,None)
            for row in csvreader:
                _,created = User.objects.get_or_create(
                    full_name = row[0],
                    username = row[1],
                    email_id = row[2],
                    external_url = row[8],
                    brands_worked_with = 
                _,stats = User_Statistics.objects.get_or_create(
                    username =User.objects.get() )

What query/function should I write in User_Statistics so that both the tables are syncronized.

Upvotes: 0

Views: 595

Answers (1)

radoh
radoh

Reputation: 4809

get_or_create() returns a tuple:

Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.

but you seem to ignore the returned object (by using _). Instead you might want to use the returned object and reference it in subsequent User_Statistics object creation. I.e.:

user, created = User.objects.get_or_create(...)
stats, created = User_Statistics.objects.get_or_create(
    username=user,
    ...other properties...
)

Upvotes: 2

Related Questions