0

我试图让我的一些 ForeignKey 关系出现在我的 TastyPie 输出中。这是我的模型:

class Report(models.Model):
    safetyreportid = models.SlugField("Safey Report Unique Identifier", max_length=125, primary_key=True)
    safetyreportversion = models.IntegerField("Safety Report Version Number", max_length=125, blank=True, null=True)
    primarysourcecountry = models.CharField("Country of the primary reporter", max_length=3, blank=True)
    occurcountry = models.CharField("Country where the event occured", max_length=3, blank=True)

class Reaction(models.Model):
    report = models.ForeignKey(Report)
    reactionmeddrapt = models.CharField("MedDRA Preferred Term used to characterize the event", max_length=250, blank=True)
    reactionmeddraversionpt = models.CharField("MedDRA version for reaction/event term PT", max_length=100, blank=True)

和我的 API.py 文件:

class ReactionResource(ModelResource):
    class Meta:
        queryset = Reaction.objects.all()
        resource_name = 'reaction'

class ReportResource(ModelResource):
    reaction = fields.ForeignKey(ReactionResource, attribute='reaction', full=True, null=True)
    class Meta:
        queryset = Report.objects.all()
        resource_name = 'report'

但是,即使存在关系(我可以在 django 管理面板中看到),我在 JSON 输出中得到的只是:

reaction: null,

有任何想法吗?

4

2 回答 2

1

你们的关系看起来颠倒了。

ForeignKey模型之间的- Reaction> Report,但在您的 API 中,它是ReportResource-> ReactionResource

于 2013-08-27T19:45:35.257 回答
0

如果您想查看报告中的反应,您的问题的正确答案是包含从资源ReportReaction资源的反向外键:

class ReportResource(ModelResource):
    reaction_set = fields.ToManyField('yourapp.resources.ReactionResource', 'reaction_set', full=False)
    class Meta:
        queryset = Report.objects.all()
        resource_name = 'report'

class ReactionResource(ModelResource):
    report = fields.ForeignKey(ReportResource, 'report', full=True, null=True)
    class Meta:
        queryset = Reaction.objects.all()
        resource_name = 'reaction'

此 ToManyField 将显示该reaction_set字段中的所有反应资源 URI。鉴于尚未声明资源,资源的名称必须是完整的字符串路径。希望能帮助到你。

于 2013-09-02T14:14:58.157 回答