Django tastypie在两个相关模型中创建资源

时间:2014-10-25 07:44:08

标签: python django rest tastypie

我有两个模型,我想为model1设置一个api,当POSTed应该在model1和model2中创建资源,其中model2通过外键与model1相关。请查找我的模型和资源供您参考,

class model1(models.Model):
   name = models.CharField(max_length = 60)


class model2(models.Model):
  var = models.BooleanField()
  modelid = models.ForeignKey(model1,related_name = 'amenities')


class model1Resource(ModelResource):
  amenities = fields.ToManyField(model2Resource,'amenities',full = True)  
  class  Meta:
     authorization = Authorization()
     queryset = model1.objects.all()
     resource_name = 'postrequirement'
     allowed_methods = ['post']

class model2Resource(ModelResource):
  class Meta:
     queryset = model2.objects.all()
     resource_name = 'getamenities'
     allowed_methods = ['get','post']

1 个答案:

答案 0 :(得分:0)

使用Manager类:

class model2Manager(models.Manager):
    def createModel2WithAmenity(self, var, name):
        m2 = self.create(var=var)
        m2.modelid_set.create(name=name)

class model2:
    ....
    objects = model2Manager()

调用model2.createModel2WithAmenity(var,name)来创建该对。