I need to create object "Tag" with relationship many-to-many attached to object "Task".I have this code and don't understand why it doesn't work. I see error Cannot resolve keyword 'task' into field. Choices are: id, name, tags, P.S. I relied on this post manyToMany with django rest framework
.models
class Tag(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return "{}".format(self.name)
class Task(models.Model):
name = models.CharField(max_length=200, blank=True)
tags = models.ManyToManyField(Tag)
def __str__(self):
return "{}".format(self.name)
.views
class TagCreateView(generics.ListCreateAPIView):
serializer_class = TagSerializer
def get_queryset(self):
queryset = Tag.objects.all()
task_id = self.kwargs.get('task_id', None)
if task_id is not None:
queryset = queryset.filter(task=task_id)
return queryset
def perform_create(self, serializer):
task_id = self.kwargs.get('task_id', None)
try:
tasks = Task.objects.get(task__id__exact=task_id)
except Task.DoesNotExist:
raise NotFound()
serializer.save(tag=tasks)
.serielizers
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = ('id', 'name','')
class TaskSerializer(serializers.ModelSerializer):
tag = TagSerializer(many=True, read_only=True)
class Meta:
model = Task
fields = ('id', 'name', 'tags')
read_only_fields = ('tags')
.urls
urlpatterns = {
url(r'^todolists/(?P<task_id>[0-9]+)/tags', TagCreateView.as_view(), name="tags")}
If you're not hung up on creating intermediate and other table records in one HTTP request. Otherwise you've got to handle nested representations.
models.py
:api.py
:After that you can
You need to handle the nested serializers creation in the serializers
create
method;As in here: http://www.django-rest-framework.org/api-guide/serializers/#writing-create-methods-for-nested-representations