Django 未通过TastyPie表示的外键

Django 未通过TastyPie表示的外键,django,tastypie,Django,Tastypie,我正试图在我的Tastype输出中显示我的一些外键关系。这是我的模型: class Report(models.Model): safetyreportid = models.SlugField("Safey Report Unique Identifier", max_length=125, primary_key=True) safetyreportversion = models.IntegerField("Safety Report Version Number", ma

我正试图在我的Tastype输出中显示我的一些外键关系。这是我的模型:

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,

有什么想法吗?

你们的关系看起来颠倒了


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

如果您想查看报告中的反应,正确的答案是将
报告
中的反向外键添加到
反应
参考资料中:

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将在
反应集
字段中显示所有反应资源URI。资源的名称必须是完整的字符串路径,因为资源尚未声明。希望有帮助。

你能发布一个不起作用的
safetyreportid
示例吗?{occurcountry:,primarysourcecountry:,reaction:null,resource_uri:“/api/report/8480347-2/”,safetyreportid:“8480347-2”,safetyreportversion:null,},否则我如何将该报告与内部的多个反应联系起来呢,下面是关于tastypie文档的教程中的示例所读到的内容——我是否遗漏了什么@seanherron在Tastypie的示例中,
ForeignKey
在模型和资源中都是
Entry
->
User
。您的代码并非如此。@seanherron让API使用者访问报告并过滤反应可能更容易。如果你真的想在报告中包含反应,你可以使用,但我建议不要使用。