Django related_name 导入对象而不是 foreign_keys

Django related_name import Objects instead of foreign_keys

当我在 db.sqlite3 中导入我的 CSV 文件时,我不知道如何导入 foreign_key 而不是“对象”。

这是我试过的。

# 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 管理面板:添加记录

谢谢帮助

您是否正在寻找这个:foreignkey_id 来设置这个字段

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')

要在 django 管理面板中显示不同的名称,您需要在 admin.py 中注册您的模型,如下所示

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)
class Site(Model):
    name = models.CharField(max_length=5, unique=True, help_text="Site Local")
    objects = models.Manager()

    def __str__(self):
        return self.name

如果您想在管理面板中显示 Site 名称而不是对象,那么您需要向模型添加 str 方法class