django-import-export:包含许多字段的ForeignKey

时间:2018-02-15 22:36:27

标签: python django export-to-excel django-import-export

我只需要从我的管理员导出数据。我的代码现在看起来像:

models.py

 from django.db import models
from services.models import Services,PromoCodes,CauseOfReservedPromocodes
# Create your models here.

class User(models.Model):
    name=models.CharField(max_length=200)
    surname=models.CharField(max_length=200)
    email=models.EmailField()
    password=models.CharField(max_length=200)
   telephone=models.PositiveIntegerField(max_length=12,blank=True,null=True)
    userRequest=models.ForeignKey('UsersRequests', blank=True, null=True, on_delete=models.CASCADE)

    def __str__(self):
        return self.name + " " + self.surname


class UsersRequests(models.Model):
    date = models.DateField()
    requestChannel = models.CharField(max_length=30)
    problem = models.CharField(max_length=200)
    solution = models.CharField(max_length=200)

    def __unicode__(self):
        return str(self.date) + " " + str(self.requestChannel) + " " + str(self.problem) + " " + str(self.solution)

我的admin.py是:

from django.contrib import admin
from .models import User,UsersRequests
from import_export import resources, widgets, fields
from import_export.admin import ImportExportModelAdmin,ExportMixin

class UsersResource(resources.ModelResource):
 class Meta:
        model = User
        fields = ('id', 'name', 'email', 'telephone', 'userRequest')

class UserAdmin(ImportExportModelAdmin):
    resource_class = UsersResource

@admin.register(User)
class UserAdmin(ImportExportModelAdmin):
    search_fields = ('name', 'surname', 'email', 'telephone')

我尝试了一切来使userRequest工作,但它只为userRequest发送整数 - id。如何从类UsersRequests(models.Model)获取完整数据?

1 个答案:

答案 0 :(得分:0)

您应该准确指出所有相关字段,例如:

class UsersResource(resources.ModelResource):
    class Meta:
        model = User
        fields = ('id', 'name', 'email', 'telephone',
        'userRequest__date', 'userRequest__problem')

@admin.register(User)
class UserAdmin(ImportExportModelAdmin):
    resource_class = UsersResource
    search_fields = ('name', 'surname', 'email', 'telephone')

等等