编辑2:我取得了一些进展并更新了我的代码,如下所示:
我在models.py中有这三个模型:
class Variables(models.Model):
variableid = models.IntegerField(db_column='VariableID', primary_key=True)
variableName = models.CharField(db_column='VariableNameCV', max_length=255)
class Meta:
managed = False
db_table = 'variables'
class Results(models.Model):
resultid = models.BigIntegerField(db_column='ResultID', primary_key=True)
variable = models.ForeignKey('Variables', related_name='results', db_column='VariableID')
units = models.ForeignKey('Units', related_name='units', db_column='UnitsID')
class Meta:
managed = False
db_table = 'results'
class Units(models.Model):
unitsid = models.IntegerField(db_column='UnitsID', primary_key=True)
unitstype = models.CharField(db_column='UnitsTypeCV', max_length=255)
unitsname = models.CharField(db_column='UnitsName', max_length=255)
class Meta:
managed = False
db_table = 'units'
我定义了这些tastypie模型资源:
class UnitsResource(ModelResource):
class Meta:
queryset = Units.objects.all()
resource_name = 'units'
collection_name = 'units'
authorization = Authorization()
serializer = Serializer()
class ResultsResource(ModelResource):
units = fields.ForeignKey(UnitsResource, attribute='units', full=True, null=True);
class Meta:
queryset = Results.objects.all()
resource_name = 'results'
collection_name = 'results'
authorization = Authorization()
serializer = Serializer()
class VariablesResource(ModelResource):
results = fields.ToManyField(ResultsResource, attribute='results', related_name='results', full=True, null=True);
class Meta:
queryset = Variables.objects.all()
resource_name = 'variables'
collection_name = 'variables'
authorization = Authorization()
serializer = Serializer()
现在输出是这样的:
<variable>
<variableName>...</variableName>
<variableid>...</variableid>
<result type="list">
<object>
<resultid>...</resultid>
<units>
<unitname>...</unitname>
<unittype>...</unittype>
</units>
</object>
</variable>
我在请求此网址(http://127.0.0.1:8000/api/v1/variables/4/
)时尝试获取以下输出:
<variable>
<variableName>...</variableName>
<variableID>...<variableID>
<unit>
<unitName>...</unitName>
<unitType>...</unitType>
</unit>
</variable>
我知道我必须通过ResultsResource
才能访问UnitsResource
,但是如何让我的XML输出忽略来自ResultsResource
的内容?作为一个附带问题,我可以查看哪些文档来帮助我解决这个问题?
答案 0 :(得分:0)
我想我已经找到了我需要的东西。这产生了我想要的结果:
class VariablesResource(ModelResource):
results = fields.ToManyField(ResultsResource, attribute='results', related_name='results', full=True, null=True);
class Meta:
queryset = Variables.objects.all()
resource_name = 'variables'
collection_name = 'variables'
authorization = Authorization()
serializer = Serializer()
def dehydrate(self, bundle):
variablesBundle = {}
unitsBundle = {}
for k, v in bundle.data.iteritems():
if (k != u'results'):
variablesBundle[k] = v
else:
for i in v:
unitsBundle = i.data['units']
variablesBundle['unit'] = unitsBundle
return variablesBundle