【问题标题】:Getting a field value from a field via a ForeignKey widget in reverse with django-import-export使用 django-import-export 反向通过 ForeignKey 小部件从字段中获取字段值
【发布时间】:2017-08-16 23:48:18
【问题描述】:

我几乎可以正常工作了。

型号:

class Child(models.Model):
    parent = models.ForeignKey('project.Parent')
    name = models.CharField(max_length=100)

class Parent(models.Model):
    text = models.CharField(max_length=100)

资源:

class ParentResource(resources.ModelResource):
    children = fields.Field(widget=widgets.ForeignKeyWidget(Parent))

    class Meta:
        model = Parent
        use_transactions = True
        fields = ('text', 'children__child__name')

然后视图调用资源并下载它。问题是,名字是空白的。所以,其他一切都很好,但我不能让 child.name 出现。我错过了什么?

【问题讨论】:

    标签: django django-import-export


    【解决方案1】:

    首先,modelA 使用widgets.ForeignKeyWidget 来查找相关的modelB modelA 的ForeignKey

    ChildResource 可以使用widgets.ForeignKeyWidget 查找Parent,但反之则不行。

    反向执行,即循环和/或显示来自ParentResource 的一组Childs(具有ForeignKey Parent)的某些字段,您需要做这样的事情:

    from import_export import fields, resources
    from .models import Parent
    
    
    class ParentResource(resources.ModelResource):
    
        children = fields.Field()
    
        class Meta:
            model = Parent
            use_transactions = True
            fields = ('text', 'children')
    
        def dehydrate_children(self, parent):
            children = list(parent.child_set.all())
            return ','.join([child.name for child in children])
    

    使用dehydrate() 方法。然后,当您导出ParentResource 时,您将获得一个带有“children”键的数据集对象,其值是以逗号分隔的子项名称列表。

    【讨论】:

    • 但是你也想导入数据怎么办呢?
    猜你喜欢
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 2021-04-04
    • 2015-05-08
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    相关资源
    最近更新 更多