我刚刚设置了整个import-export东西,但是我不能使它使用外键从另一个模型中导出字段。
models.py
from django.db import models
from django.contrib.auth.models import User
from datetime import date
from .validators import validate_file_size
# Create your models here.
class CORMeserii(models.Model):
CodCOR = models.CharField(max_length=25, primary_key=True, unique=True)
MeserieCor = models.CharField(max_length=50, unique=True)
def __str__(self):
return str(self.CodCOR + " - " + self.MeserieCor)
class Meta:
verbose_name_plural = "CORuri"
class Oferta(models.Model):
solicitant = models.ForeignKey(User, on_delete=models.CASCADE)
cor = models.ForeignKey(CORMeserii, on_delete=models.CASCADE)
dataSolicitare = models.DateField(default=date.today)
locuri = models.IntegerField()
agentEconomic = models.CharField(max_length=50)
adresa = models.CharField(max_length=150)
dataExpirare = models.DateField()
experientaSolicitata = models.CharField(max_length=200)
studiiSolicitate = models.CharField(max_length=200)
judet = models.CharField(max_length=20)
localitate = models.CharField(max_length=25)
telefon = models.CharField(max_length=12)
emailContact = models.EmailField(max_length=40)
rezolvata = models.BooleanField(default=False)
def __str__(self):
return str(self.cor)
admin.py
from django.contrib import admin
from .models import Oferta, CORMeserii
from import_export import resources
from import_export.admin import ImportExportMixin, ImportExportModelAdmin
import tablib
# Register your models here.
class CorImEx(resources.ModelResource):
class Meta:
model = CORMeserii
class CorAdmin(ImportExportMixin, admin.ModelAdmin):
list_display = ('CodCOR', 'MeserieCor')
resource_class = CorImEx
class CorImExAdmin(ImportExportModelAdmin):
resource_class = CorImEx
class OferteImEx(resources.ModelResource):
class Meta:
model = Oferta
fields = ('id', 'solicitant', 'cor', 'oferta.cor.MeserieCor')
class OfertaAdmin(ImportExportMixin, admin.ModelAdmin):
list_display = ('id', 'solicitant', 'dataExpirare', 'dataSolicitare')
resource_class = OferteImEx
class OferteImExAdmin(ImportExportModelAdmin):
resource_class = OferteImEx
admin.site.register(Oferta, OfertaAdmin)
admin.site.register(CORMeserii, CorAdmin)
您可以在OferteImEx类-“ oferta.cor.MeserieCor”字段中看到它。
我想从模型CORMeserii中导出MeserieCor字段-但我无法弄清楚。
我尝试使用:“ oferta.cor.MeserieCor”, cor.MeserieCor”,“ MeserieCor”(即使后两个对我来说根本没有意义)。
是否有某种方式可以导出该字段,即使它来自其他模型也是如此? (我很确定有,但我不知道)
谢谢。
答案 0 :(得分:1)
在Django中,您使用双下划线(__)来跟踪查找中的关系。在文档中:
Django提供了一种强大而直观的方法来“跟踪”查找中的关系,并在幕后自动为您处理SQL JOIN。要建立关系,只需在各个模型之间使用相关字段的字段名称,并用双下划线将其隔开,直到找到所需字段为止。
链接:Lookups that span relationship
django import export 文档中甚至有一个如何遵循关系的示例:
定义ModelResource字段时,可以遵循模型关系:
class BookResource(resources.ModelResource):
class Meta:
model = Book
fields = ('author__name',)