我刚刚开始使用
django tastypie,而且我很喜欢它.
我的问题:我正在搜索与管理视图中相同的功能:
为foreignkey字段指定在其他对象的列表响应中看到的内容以及详细响应中的内容.
我的问题:我正在搜索与管理视图中相同的功能:
为foreignkey字段指定在其他对象的列表响应中看到的内容以及详细响应中的内容.
让我们说这是我简化的模型:
class Location(models.Model):
name = models.CharField(max_length=256,blank=True)
longitude = models.FloatField(blank=True,default=0.0)
latitude = models.FloatField(blank=True,default=0.0)
description = models.CharField(max_length=256,blank=True)
shortname = models.CharField(max_length=256,blank=True)
tooltiptext = models.CharField(max_length=1000,blank=True)
locationtype = models.ForeignKey(LocationType,blank=True,null=True)
public_anonymous = models.BooleanField(default=False,blank=False,null=False)
public_authorized = models.BooleanField(default=False,null=False)
def __str__(self):
return '%s' % (self.name)
class Variable(models.Model):
abbreviation = models.CharField(max_length=64,unique=True)
name = models.CharField(max_length=256,blank=True)
unit = models.CharField(max_length=64,blank=True)
def __str__(self):
return '%s [%s]' % (self.name,self.unit)
class Timeseries(models.Model):
locationkey = models.ForeignKey(Location)
variablekey = models.ForeignKey(Variable)
tstypekey = models.ForeignKey(TimeseriesType)
def __str__(self):
return '%s: %s (%s)' % (self.locationkey.name,self.variablekey.name,self.tstypekey.name)
这些是api的资源:
class LocationResource(ModelResource):
class Meta:
queryset = Location.objects.all()
resource_name = 'location'
excludes = ['public_anonymous','public_authorized']
authentication = BasicAuthentication()
authorization = DjangoAuthorization()
class VariableResource(ModelResource):
class Meta:
queryset = Variable.objects.all()
resource_name = 'variable'
authentication = BasicAuthentication()
authorization = DjangoAuthorization()
class TimeseriesTypeResource(ModelResource):
class Meta:
queryset = TimeseriesType.objects.all()
resource_name = 'timeseriestype'
authentication = BasicAuthentication()
authorization = DjangoAuthorization()
class TimeseriesResource(ModelResource):
location = fields.ForeignKey(LocationResource,'locationkey',full=False)
variable = fields.ForeignKey(VariableResource,'variablekey',full=False)
timeseriestype = fields.ForeignKey(TimeseriesTypeResource,'tstypekey',full=False)
class Meta:
queryset = Timeseries.objects.all()
resource_name = 'timeseries'
authentication = BasicAuthentication()
authorization = DjangoAuthorization()
在TimeseriesResource中,如果你使用full = False,你只需要一个带有id的url,如果你使用full = True,你将获得所有信息.实际上,该位置有更多的信息.
我需要比full =’False’更多的信息,但不是所有使用full = True的信息.
我不想使用exclude选项,因为我没有详细信息或Location对象列表中的信息.
我正在考虑的其中一个选项是为同一个对象制作2个资源,但这并不是最好的解决方案(但我想它会起作用).
顺便说一句:我想过这个选项,不会工作(当然),更好地使用bmihelac(谢谢)答案中的解决方法.
虽然…
尝试解决方法……
引导我提出一个新问题,请参阅:
django-tastypie: Cannot access bundle.request in dehydrate(self,bundle)
解决方法
show和index中有不同字段的功能请求,还有一些讨论如何实现它:
https://github.com/toastdriven/django-tastypie/issues/18
在此功能未包含之前,您可以帮助解决此问题:
https://github.com/toastdriven/django-tastypie/issues/18#issuecomment-2695447