我试图让我的一些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,
有什么想法吗?
答案 0 :(得分:1)
你的关系看起来相反。
模型之间的ForeignKey
Reaction
- > Report
,但在您的API中,它是ReportResource
- > ReactionResource
。
答案 1 :(得分:0)
问题的正确答案,如果您想查看报告中的反应,请包含从Report
到Reaction
资源的反向ForeignKey:
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。在资源尚未声明的情况下,资源的名称必须是完整的字符串路径。希望它有所帮助。