基本上我正在学习如何通过我的rest api的url正则表达式来过滤结果的教程。我希望转到/ api / v1 / users / 1 /目标以获取与用户相关的目标列表。我已经搜索了django休息框架文档和大量的教程,但无法使其工作。我收到404错误,我要求的网址不存在。
myapp.views.py
class ListCreateUser(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = serializers.UserSerializer
class RetrieveUpdateDestroyUser(generics.RetrieveUpdateDestroyAPIView):
queryset = User.objects.all()
serializer_class = serializers.UserSerializer
class ListCreateGoal(generics.ListCreateAPIView):
queryset = Goal.objects.all()
serializer_class = serializers.GoalSerializer
def get_queryset(self):
return self.queryset.filter(user_id=self.kwargs.get('user_pk'))
class RetrieveUpdateDestroyGoal(generics.RetrieveUpdateDestroyAPIView):
queryset = Goal.objects.all()
serializer_class = serializers.GoalSerializer
urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/v1/users', include('dataStoreApp.urls', namespace='users')),
]
myapp.urls.py
urlpatterns = [
url(r'^$',
views.ListCreateUser.as_view(),
name='user_list'),
url(r'(?P<pk>\d+)/$',
views.RetrieveUpdateDestroyUser.as_view(),
name='user_detail'),
url('r^(?P<user_pk>\d+)/goals/$',
views.ListCreateGoal.as_view(),
name='goals_list'),
url('r^(?P<user_pk>\d+)/goal/(?P<pk>\d+)/$',
views.RetrieveUpdateDestroyGoal.as_view(),
name='user_goal_detail'),
]
myapp.serializers.py
class GoalSerializer(serializers.ModelSerializer):
class Meta:
model = Goal
fields = ('id', 'user_id', 'name', 'amount',
'start_date', 'end_date', )
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'email', 'id', 'password')
read_only_fields = ('id', )
extra_kwargs = {'password': {'write_only': True}}
myapp.models.py
class Goal(models.Model):
class Meta:
verbose_name_plural = 'Goals'
user_id = models.ForeignKey(settings.AUTH_USER_MODEL, default=1,
on_delete=models.CASCADE)
NAME_CHOICES = (
("Goal 1", "Goal 1"),
("Goal 2", "Goal 2"),
("Goal 3", "Goal 3"),
)
name = models.CharField(max_length=100)
amount = models.DecimalField(decimal_places=2, max_digits=20)
start_date = models.DateField(default=None, blank=True, null=True)
end_date = models.DateField(default=None, blank=True, null=True)
def __str__(self):
return self.name