【问题标题】:Tastypie: how to set default value for a m2m field?Tastypie:如何为 m2m 字段设置默认值?
【发布时间】:2012-09-11 21:08:10
【问题描述】:

我想做的是为 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 的秘诀是什么?
  • 如果没有,正确的做法是什么?
  • 我注意到 sweetpie ManyToMany 字段有一个默认选项。在这种情况下如何使用它或者我在哪里可以找到关于它的完整文档..

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    在 django-tastypie 端有两种可能的方法来处理 m2m 关系。

    一个 to 覆盖 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 请求来实现。

    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/
    

    【讨论】:

    • 太好了,它有效!我真希望他们能很好地记录这一点!
    猜你喜欢
    • 2019-03-23
    • 2013-12-29
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    相关资源
    最近更新 更多