0

I am a beginner in programming, I use Django + Django ninja in my project. Now stuck on the moment of creating endpoints I'm trying to make a filter to add tags to an article and check if the tag exists. Here is the piece of code I'm currently working on:

    @router.post('/article', response={200: schema.ArticleOut, 500: schema.Error})
    def create_article(request, tags_id: List[int], payload: schema.ArticleIn):
        try:
            for tag in tags_id:
                if tag > 0:
                    qs = models.Article.objects.create(**payload.dict())
                    qs.save()
                    current_article = get_object_or_404(models.Article, pk=qs.id)
                    e = models.Tag.objects.get(pk=tag)
                    current_article.tags.add(e)
                    return 200, qs
                else:
                    return 500, {'msg': 'No Tags'}        
        except:
            return 500, {'msg': 'Not'}

Tell me, does it make sense to do this in the request, if so, how best to implement it? Maybe there are other approaches?

metersk
  • 11,803
  • 21
  • 63
  • 100
meha
  • 13
  • 3

1 Answers1

0

my brother helped me, he came with this solution:

def create_article(request, tags_id: List[int], payload: schema.ArticleIn):
    try:
        tags = models.Tag.objects.filter(pk__in=tags_id)
        qs = models.Article.objects.create(**payload.dict())
        qs.save()
        qs.tags.set(tags)
        return 200, qs
    except Exception as e:
        return 500, {'msg': f'Not: {str(e)}'}
meha
  • 13
  • 3