如何在rest_framework序列化器中使用pre_save方法?

时间:2018-01-25 12:13:42

标签: django django-rest-framework

我知道这是关于DRF的noob问题。我使用的是DjangoDRF的最新版本。在我的Django中,我使用pre_save signals.

在方法中创建了slug
    def create_slug(instance, new_slug=None):
      slug = slugify(instance.title)
      if new_slug is not None:
        slug = new_slug
      qs = Article.objects.filter(slug=slug).order_by("-id")
      exists = qs.exists()
      if exists:
        new_slug = "%s-%s" %(slug, qs.first().id)
        return create_slug(instance, new_slug = new_slug)
      return slug



@receiver(pre_save, sender = Article)
def pre_save_article_receiver(sender, instance, raw, using, **kwargs):
    if not instance.slug:
      instance.slug = create_slug(instance)

pre_save.connect(pre_save_article_receiver, sender=Article)

然后我可以设法使用DRF编写视图和序列化器

from rest_framework import serializers
from yogavidya.apps.articles.models import Article

class ArticleSerializer(serializers.ModelSerializer):

  class Meta:
    model = Article
    fields = [
      "title",
      "user",
      "content",
      "excerpt",
    ]

- views.py -

app_name = 'articles'
class ArticleListView(generics.ListCreateAPIView):
                  lookup_field = 'pk'
                  serializer_class = ArticleSerializer
                  queryset = Article.objects.all()

                  def list(self, request):
                        # Note the use of `get_queryset()` instead of `self.queryset`
                        queryset = self.get_queryset()
                        serializer = ArticleSerializer(queryset, many=True)
                        print(serializer.data)
                        return Response(serializer.data)
                  def get_queryset(self):
                    return Article.objects.all()

                  def get_object(self):
                    pk = self.kwargs.get("pk")
                    return Article.objects.get(pk=pk)

                  def put(self, request, *args, **kwargs):
                        return self.update(request, *args, **kwargs)
    class ArticleViewSet(viewsets.ModelViewSet):
                """
                API endpoint that allows users to be viewed or edited.
                """
                queryset = Article.objects.all().order_by('-title')
                serializer_class = ArticleSerializer

当我发布表单时,我得到name 'create_slug' is not defined。覆盖我的保存方法和更新的最佳位置在哪里?你能帮助我吗 ?

由于

1 个答案:

答案 0 :(得分:2)

我猜错误是由于def create_slug

的错误缩进造成的
Class Xyz:
    ...
    ...

def create_slug(instance, new_slug=None):
      slug = slugify(instance.title)
      if new_slug is not None:
        slug = new_slug
      qs = Article.objects.filter(slug=slug).order_by("-id")
      exists = qs.exists()
      if exists:
        new_slug = "%s-%s" %(slug, qs.first().id)
        return create_slug(instance, new_slug = new_slug)
      return slug

它不是一个类函数,所以它应该在课外。