When I importing my CSV file in db.sqlite3, I don't know how to import foreign_key instead of "Object".
This is what I've tried.
# import_csv.py (manage.my custom command)
import csv
from django.core.management.base import BaseCommand
from models import Site, Association
class Command(BaseCommand):
help = "Import Command"
def handle(self, *args, **options):
with open(_file, newline='') as csvfile:
reader = csv.DictReader(csvfile, delimiter=";")
for row in reader:
localsite, created = Site.objects.get_or_create(name=row["locSite"])
distantsite, created = Site.objects.get_or_create(name=row["disSite"])
csv_line, created = Association.objects.get_or_create(
localName=row["Name"],
locSite=localsite.id,
disSite=distantsite.id,
...
)
# models.py
class Site(models.Model):
name = models.CharField(max_length=5, unique=True, help_text="Site Local")
objects = models.Manager()
class Association(models.Model):
localName = models.CharField(max_length=50, help_text="Nom Local")
locSite = models.ForeignKey(Site, null=True, on_delete=models.SET_NULL, related_name='local_site_set')
disSite = models.ForeignKey(Site, null=True, on_delete=models.SET_NULL, related_name='distant_site_set')
Django Admin panel : add record
Thx for help