关于tastypie和在一个RESTful资源中映射多个模型类



我正在使用django+tastypie+postgreSQL做一个web应用程序的后端。然后,在另一个"项目"上,我的朋友正在实现一个前端whitch,它将利用我的后端API创建AJAX调用,从而用一些数据填充html。好的。到目前为止,我知道怎么做。

当为Restful API创建不同的资源时,问题就来了。我有,我的模型的一部分定义如下:

# COUNTRY + MANAGER
class CountryManager(models.Manager):
def create(**kwargs):
try:
country = Country.objects.get(short_name=kwargs['short_name'])            
except:
country = Country(name=kwargs['name'], short_name=kwargs['short_name'])
country.save()
return country
class Country(models.Model):
short_name = models.CharField(max_length=max_short_len, unique=True)  
name = models.CharField(max_length=max_short_len, unique=False)
lat = models.DecimalField(max_digits=11, decimal_places=9, default=0.0)
lon = models.DecimalField(max_digits=12, decimal_places=9, default=0.0)
objects = CountryManager()
# REGION +`MANAGER
class RegionManager(models.Manager):
def create(**kwargs):
try:
region = Region.objects.get(short_name=kwargs['short_name'])            
except:
region = Region(name=kwargs['name'], short_name=kwargs['short_name'], country=kwargs['country'])
region.save()
return region
class Region(models.Model):
name = models.CharField(max_length=max_short_len, unique=False, default='NoName')
short_name = models.CharField(max_length=max_short_len, unique=False, default='NoName')  
lat = models.DecimalField(max_digits=11, decimal_places=9, default=0.0)
lon = models.DecimalField(max_digits=12, decimal_places=9, default=0.0)
country = models.ForeignKey('Country')
objects = RegionManager()
# CITY + MANAGER
class CityManager(models.Manager):
def create(**kwargs):
try:
city = City.objects.get(short_name=kwargs['short_name'])
city.lat = kwargs['lat']
city.lon = kwargs['lon']            
except:
city = City(name=kwargs['name'], short_name=kwargs['short_name'], lat=kwargs['lat'], lon=kwargs['lon'])
city.save()
return city
class City(models.Model):
name = models.CharField(max_length=max_short_len, unique=False)
short_name = models.CharField(max_length=max_short_len, unique=False, default='NoName')
lat = models.DecimalField(max_digits=11, decimal_places=9, default=0.0)
lon = models.DecimalField(max_digits=12, decimal_places=9, default=0.0)
region = models.ForeignKey('Region')
objects = CityManager()

现在,如果可能的话,我想将我的/位置资源映射为城市、地区和国家的混合。因此,例如,如果我获取/api/location/1,我将获得一个JSON,其中包含以下内容:

{"location":[
{"city":"London", 
"region":"London", 
"country":"UK"
}]
}

此外,如果我POST/api/location/1,提供一个JSON,我想调用模型文件中City类中的一个方法:

def saveLocation(**kwargs):
# countryN, countrySN, regionN='No region', regionSN='No region', cityN, citySN, cityLat, cityLon, locationType
# define args
countryN = kwargs.get('countryN', None)
countrySN = kwargs.get('countrySN', None)
regionN = kwargs.get('regionN', None)
regionSN = kwargs.get('regionSN', None)
cityN = kwargs.get('cityN', None)
citySN = kwargs.get('citySN', None)
cityLat = kwargs.get('cityLat', None)
cityLon = kwargs.get('cityLon', None)
locationType = kwargs.get('locationType', None)
# put nulls in the args
if regionN is None: regionN = 'No region'
if regionSN is None: regionSN = 'No region'
# control over the params
if regionSN is None or countrySN is None or citySN is None: raise Exception('Invalid parameters')
#Save the country    
country = Country.objects.create(name=countryN, short_name=countrSN)
countryId = country.pk
#Save the region, if any. Else save it like "no region"
region = Region.objects.create(name=regionN, short_name=regionSN, country = country)
regionId = region.pk
#Save the city
city = City.objects.create(name=cityN, short_name=citysN, lat=cityLat, lon=cityLon, region=regionId)
return city

我遵循了Tastypie手册(http://django-tastypie.readthedocs.org/en/latest/cookbook.html)但它只适用于resource=model环境。

此外,我尝试实现我自己的类MyResource(Resource),以避免ModelsResource所做的直接模型映射。但我没有这样做的技能或知识

我想请求一些git repo,或者一些示例代码,在那里我可以学习如何使用Django实现Restful API,而不需要resource=model。

提前谢谢。

我认为您应该创建一个Location模型,或者使用City模型作为基础。想想看,"真正"的位置是城市,是地域和国家的传承。

对此,我的建议是创建一个简单的资源(而不是模型资源)并实现您需要的方法:

POST部分的obj_create(创建):https://github.com/toastdriven/django-tastypie/blob/master/tastypie/resources.py#L1018
  • 用于获取位置列表的obj_get_list(GET/location/):https://github.com/toastdriven/django-tastypie/blob/master/tastypie/resources.py#L967

  • 用于获取单个位置(/location/1/)的obj_get:https://github.com/toastdriven/django-tastypie/blob/master/tastypie/resources.py#L992

  • 这应该涵盖了你所需要的一切。看看ModelResource,看看这些方法是如何实现的。

    最新更新