我想要做的是设置m2m字段的默认值,我在post_save信号中进行设置。这是最小的代码:
# models.py
class Question(models.Model):
options = models.ManyToManyField(Option)
body = models.CharField(max_length=140)
def default_options(sender, instance, created, **kwargs):
if created and not instance.options.all():
options = Option.objects.filter(id__in=[1, 2])
instance.options.add(*options)
instance.save()
post_save.connect(default_options, sender=Question)
当调用“普通”保存时,它工作正常:
>>> q=Question(body='test')
>>> q.save()
>>> q.options.all()
[<Option[1]>, <Option[2]>]
但是,如果模型与tastypie挂钩,则永远不会设置选项..
# api.py
class QuestionResource(ModelResource):
options = fields.OneToManyField('qa.api.OptionResource', 'options', full=True, blank=True)
class Meta:
queryset = Question.objects.all()
# try to create a question:
curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"body":"test"}' http://localhost:8000/api/0.1/question/
服务器将回复201,但未设置问题的选项。
我的问题是:
答案 0 :(得分:2)
有两种方法可以处理django-tastypie方面的m2m
关系。
要覆盖obj_create
功能。 Here需要更多帮助。
class QuestionResource(ModelResource):
options = fields.OneToManyField('qa.api.OptionResource', 'options', full=True, blank=True)
class Meta:
queryset = Question.objects.all()
def obj_create(self, bundle, request, **kwargs):
print "hey we're in object create"
# do something with bundle.data,
return super(QuestionResource, self).obj_create(bundle, request, **kwargs)
第二种方式是通过卷曲请求来实现。
curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"body":"test", "options": ["/api/v1/option/1/"]}' http://localhost:8000/api/0.1/question/