我有两个模型,我想为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']
答案 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)来创建该对。