简体   繁体   English

Django REST框架3.1-PUT即创建mixin类,自定义lookup_field

[英]Django REST framwork 3.1 - PUT-as-create mixin class, custom lookup_field

Making use of the PUT-as-create mixin class provided HERE (class AllowPUTAsCreateMixin ): 利用此处提供的PUT-create-create mixin类(类AllowPUTAsCreateMixin ):

class Tree(models.Model):   
   myfield = models.CharField(max_length=100,unique=True)
   species = models.CharField(max_length=100, blank=True, default='')
class TreeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tree
        fields = ('myfield', 'species')
        lookup_field = 'myfield'
class TreeView(viewsets.ModelViewSet, AllowPUTAsCreateMixin):

     queryset = Tree.objects.all()
     serializer_class = TreeSerializer
     lookup_field = 'myfield'

     def update(self, request, myfield=None):
        return AllowPUTAsCreateMixin.update(self, request, lookup_field='myfield')
class AllowPUTAsCreateMixin(object):

     def update(self, request, *args, **kwargs):
          lookup_field = kwargs.pop('lookup_field')

when submitting data as JSON (using httpie): 当将数据提交为JSON(使用httpie)时:

http PUT 127.0.0.1:8000/xxx/trees/123456 < tree.json http PUT 127.0.0.1:8000/xxx/trees/123456 <tree.json

Object is created and exposed @/.../trees/{myfield} 对象已创建并公开@ / ... / trees / {myfield}

Done! 做完了!

My mistake was from poor understanding from making correct use of the kwargs. 我的错误是由于对正确使用kwargs的理解不足。 I corrected my code in the question post. 我在问题帖中更正了我的代码。

Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用django rest框架自定义lookup_field,无法解析细节 - Custom lookup_field with django rest framework, Cannot resolve detail 在 Django REST 框架中使用 lookup_field 中的相关字段 - Use a related field in lookup_field in Django REST framework Django rest框架允许lookup_field有几个选项 - Django rest framework allow lookup_field to have several options "django rest framework lookup_field 通过 OneToOneField" - django rest framework lookup_field through OneToOneField Django Rest Framework - AssertionError 修复您的 URL conf,或正确设置视图上的 `.lookup_field` 属性 - Django Rest Framework - AssertionError Fix your URL conf, or set the `.lookup_field` attribute on the view correctly Django Rest&React:lookup_field =&#39;slug&#39;不从数据库返回项目 - Django Rest & React: lookup_field = 'slug' not returning item from db DRF更改默认视图集的lookup_field以执行自定义操作 - DRF change default viewset's lookup_field for custom action lookup_field 在 Django get_queryset 中返回 None - lookup_field Return None In Django get_queryset "DRF:视图集lookup_field 配置不当" - DRF: viewsets lookup_field ImproperlyConfigured ```HyperlinkedModelSerializer```中配置不正确的lookup_field错误 - Incorrectly Configured lookup_field error in ```HyperlinkedModelSerializer```
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM