1

我想做的是为 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]>]

但是,如果模型迷上了美味派,则永远不会设置选项。

# 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 但未设置问题的选项。

我的问题是:

  • 我是否有权使用保存后信号为 m2m 字段设置默认值?
  • 如果是这样,那么美味派的秘诀是什么?
  • 如果不是,那么正确的方法是什么?
  • 我注意到 sweetpie ManyToMany 字段有一个默认选项。在这种情况下如何使用它或者我在哪里可以找到关于它的完整文档..
4

1 回答 1

2

有两种可能的方法来处理m2mdjango-tastypie 方面的关系。

一个来覆盖该obj_create功能。这里有更多帮助。

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 请求来完成。

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/
于 2012-09-11T13:08:10.520 回答