Django объект импорта related_name вместо foreigne_key
Когда я импортирую свой CSV файл в db.sqlite3, я не знаю как импортировать foreign_key вместо "Object".
Вот что я пробовал.
# 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 в класс модели
