Home > Back-end >  Django related_name import Objects instead of foreign_keys
Django related_name import Objects instead of foreign_keys

Time:05-06

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

CodePudding user response:

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

CodePudding user response:

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)
  • Related