1

我正在使用 django+tastypie+postgreSQL 做 Web 应用程序的后端。然后,在另一个“项目”中,我的朋友正在实现一个前端,它将利用我的后端 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()

现在,如果可能的话,我想将我的 /location 资源映射为城市、地区和国家的混合体。因此,例如,如果我 GET /api/location/1,我将获得一个 JSON,例如:

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

此外,如果我发布 /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),但它仅适用于资源=模型环境。

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

我想请求一些 git repo 或一些示例代码,我可以在其中学习如何在没有资源 = 模型的情况下使用 Django 实现 Restful API。

提前致谢。

4

1 回答 1

0

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

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

那应该涵盖您需要的所有内容。看看ModelResource这些方法是如何实现的。

于 2012-09-21T13:24:33.800 回答