1

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

Django Admin panel : add record

Thx for help

MrSo
  • 641
  • 8
  • 34

2 Answers2

1

Are you looking for this: foreignkey_id to set this field

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_id=localsite.id,
                    disSite_id=distantsite.id  # This is the way to add foreign key if you know or if you want to create
                    ...
                )


# 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")
    locNomSite = models.ForeignKey(Site, null=True, on_delete=models.SET_NULL, related_name='local_site_set')

To display different name in django admin panel you need to resgister your model in admin.py as follows

class CustomAssociationAdmin(admin.ModelAdmin):
    form = MyInvoiceAdminForm


class CustomAssociationAdminForm(forms.ModelForm):
    person = YourModelChoiceField(queryset=Site.objects.all()) 
    class Meta:
          model = Invoice
      
class YourModelChoiceField(forms.ModelChoiceField):
     def label_from_instance(self, obj):
         return "%s"% (obj.name)

admin.site.register(CustomAssociationAdmin, Association)
MrSo
  • 641
  • 8
  • 34
Deepak Tripathi
  • 3,175
  • 1
  • 8
  • 21
  • Same. It is diplaying "Site object (1)" .... in the select field in back office. I would like to display Site names. – MrSo May 06 '22 at 12:00
  • Thx for help. But I prefer the new answer above. – MrSo May 06 '22 at 12:13
  • 1
    @MrSo I could suggest you this method but you can read this SO https://stackoverflow.com/questions/6836740/how-to-change-foreignkey-display-text-in-the-django-admin – Deepak Tripathi May 06 '22 at 12:14
1
class Site(Model):
    name = models.CharField(max_length=5, unique=True, help_text="Site Local")
    objects = models.Manager()

    def __str__(self):
        return self.name

If you want to display the Site name in the admin panel instead of object then you need to add str method to the model class

kjaw
  • 515
  • 2
  • 9