title: Django Rest Framework - Create foreign key object on POST
body: <p>I have a simple DRF REST API that I want to use to create blog articles. I want to be able to add tags to those blog articles so users can search tags and see related articles. However, the tags may not exist yet. I have created an <code>Article</code> Model with a ForeignKey field to a <code>Tag</code> Model like this:</p>
  
  <pre><code>class Tag(models.Model):
  
      name = models.CharField(max_length=32)
  
      def _str__(self):
          return self.name
  
      class Meta:
          ordering = ('name',)
  
  class Article(models.Model):
  
      title = models.CharField(max_length=256)
      author = models.ForeignKey(User, on_delete=models.CASCADE)
      content = models.TextField()
      date = models.DateTimeField(auto_now_add=True)
      tags = models.ForeignKey(Tag, on_delete=models.CASCADE, blank=True, default=None)
  
      def __str__(self):
          return self.title
  
      class Meta:
          ordering = ('date', 'id')
  </code></pre>
  
  <p>Ideally what I want is to be able to POST a new <code>Article</code> with a set of tags, and if any of the tags don't exist, create them in the DB. However, as it is currently, the tags need to already exist to be added to the <code>Article</code>. Visually, DRF shows this as a dropdown that is populated with pre-existing tags:</p>
  
  <p><a href="https://i.stack.imgur.com/uFxgc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uFxgc.png" alt="DRF Interface"></a></p>
  
  <p>How can I add or create multiple <code>Tag</code>s from my <code>Article</code> API endpoint?</p>
  
  <p>EDIT: As requested, I've added my views.py</p>
  
  <p>views.py:</p>
  
  <pre><code>from api.blog.serializers import ArticleSerializer, TagSerializer
  from rest_framework import viewsets
  
  # /api/blog/articles
  class ArticleView(viewsets.ModelViewSet):
  
      queryset = Article.objects.all()
      serializer_class = ArticleSerializer
  
  # /api/blog/tags
  class TagView(viewsets.ModelViewSet):
  
      queryset = Tag.objects.all()
      serializer_class = TagSerializer
  </code></pre>
  
  <p>For completeness, here are my serializers from my REST API's serializers.py.</p>
  
  <p>serializers.py:</p>
  
  <pre><code>class ArticleSerializer(serializers.ModelSerializer):
  
      class Meta:
          model = Article
          fields = '__all__'
  
  
  class TagSerializer(serializers.ModelSerializer):
  
      class Meta:
          model = Tag
          fields = '__all__'
  </code></pre>
  
  <p>urls.py:</p>
  
  <pre><code>from rest_framework import routers
  
  router = routers.DefaultRouter()
  router.register('articles', views.ArticleView)
  router.register('tags', views.TagView)
  
  urlpatterns = [
      path('', include(router.urls)),
  ]
  </code></pre>