Home > Software design >  Populating sql table with foreign keys using django
Populating sql table with foreign keys using django

Time:04-12

So im having some trouble inserting data into my sql database when using django. Setting up the tables aswell as populating them trough the admin page works perfectly fine but i have a scraper function that runts every 24h thats supposed to insert data.

from datetime import datetime
from .faceScraper import faceScraper as fc


def Dbpopulator():

    from ..models import Event

    [title_list, time_list, location_list, nation_list] = fc()
    print("scraped")
    for i in range(len(title_list)):
        
        e = Event()
        
        e.title = title_list[i]
        e.starttime = time_list[i][0]
        e.endtime = time_list[i][1]
        e.location = location_list[i]
        
        instance = e.save(commit=False)
        
        instance.nation = nation_list[i]
       
        instance.save()

The problem arises when im trying to set the nation which is a foreign key from the models file below.

from django.db import models

# Create your models here.


class Nation(models.Model):
    name = models.CharField(max_length=80, primary_key=True)

    description = models.TextField()

    Facebook = models.CharField(max_length=80, null=True, blank=True)

    def __str__(self):
        return self.name


class Event(models.Model):
    title = models.CharField(max_length=80, unique=True)

    starttime = models.DateTimeField(null=True, blank=True)

    endtime = models.DateTimeField(null=True, blank=True)

    nation = models.ForeignKey(
        Nation, on_delete=models.CASCADE, default=None, null=True, blank=True)

    location = models.CharField(max_length=80, null=True, blank=True)

    def __str__(self):
        return self.title

I have tried many different ways primarily just setting the e and saving like normal, aka cutting out all the instance and commit=false.

e.nation = nation_list[i]
e.save()

But it just wont work, i am also very certain that the database is already populated with nations which contains names that corresponds to what im trying to insert as i can see thoose on the admin page. All help apreciated!

CodePudding user response:

You need to get the Nation instance first. If nation-list contains the names of the nations, you can get them like this :

e = Event()
...
e.nation = Nation.objects.get(name=nation_list[i])
e.save()

If you're not a 100% sure that provided name will match a Nation, you can use .filter(...).first() rather than .get(...) to avoid any crash.

  • Related