0
我使用django rest框架構建了一個TODO應用程序。我必須有兩種模式,即todolist和todoitem。我可以如何爲特定的todolist設置新的todoitem?我嘗試使用外鍵,但它並沒有制定出來,對不起我的英文不好,任何人都可以請幫我如何將項目設置爲Django Rest框架中的特定Todolist?
我models.py
:
class todolist(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE,default=None)
name = models.CharField(max_length=128)
creation_date = models.DateField(auto_now=True)
def __unicode__(self):
return self.name
class todoitem(models.Model):
description = models.CharField(max_length=150)
completed = models.BooleanField(default=False)
due_by = models.DateField(auto_now=True)
parent = models.ForeignKey(todolist,on_delete=models.CASCADE)
def _unicode__(self):
return self.description
我classviews.py
:
class Todolist(LoginRequiredMixin,ListCreateAPIView):
serializer_class = listserializer
def perform_create(self, serializer):
serializer.save(user=self.request.user)
def get_queryset(self):
self.queryset = todolist.objects.filter(user=self.request.user)
return super(Todolist, self).get_queryset()
class Todolistdetail(LoginRequiredMixin,RetrieveUpdateDestroyAPIView):
def get_queryset(self):
self.queryset = todolist.objects.filter(user=self.request.user)
return super(Todolistdetail, self).get_queryset()
serializer_class = listserializer
class Todoitem(LoginRequiredMixin,ListCreateAPIView):
def perform_create(self, serializer):
temp = self.queryset(todolist.objects.filter(id=self.kwargs['pk']))
serializer.save(parent=temp)
def get_queryset(self):
temp = todolist.objects.filter(id=self.kwargs['pk'])
self.queryset = todoitem.objects.filter(parent=temp)
return super(Todoitem, self).get_queryset()
serializer_class = itemserializer
class Todoitemdetail(LoginRequiredMixin,RetrieveUpdateDestroyAPIView):
def get_queryset(self):
temp = todolist.objects.filter(id=self.kwargs['list_id'])
self.queryset = todoitem.objects.filter(parent=temp)
return super(Todoitemdetail, self).get_queryset()
serializer_class = itemserializer
我serializers.py
:
class listserializer(serializers.ModelSerializer):
user = serializers.ReadOnlyField(source='user.username')
class Meta:
model = todolist
fields = '__all__'
class itemserializer(serializers.ModelSerializer):
parent = serializers.ReadOnlyField(source='todolist.id')
class Meta:
model = todoitem
fields = '__all__'
我urls.py
:
from todoapp import classviews
app_name = "todoapp"
urlpatterns = [
url(r'^list/$',classviews.Todolist.as_view(),name="list_lists"),
url(r'^list/(?P<pk>[0-9]+)/$',classviews.Todolistdetail.as_view(),name="each_list"),
url(r'^list/(?P<pk>[0-9]+)/item/$',classviews.Todoitem.as_view(),name="list_items"),
url(r'^list/(?P<list_id>[0-9]+)/item/(?P<pk>[0-9]+)/$',classviews.Todoitemdetail.as_view(),name="each_item")
]