如何在Django中使用ForeignKey属性获取get请求?

时间:2017-09-22 06:02:49

标签: django django-models django-rest-framework

基本上我想制作一个get方法,当用person_id填充时,以json格式列出该人的所有地址。已经尝试了许多其他方法,但没有一个接近

models.py

from django.db import models
from django.core.validators import RegexValidator

# Create your models here.

class Address(models.Model):
    zipcode = models.CharField(max_length=8)
    state = models.CharField(max_length=100)
    city = models.CharField(max_length=100)
    street = models.CharField(max_length=100)
    number = models.IntegerField()
    person_id = models.ForeignKey('Person', on_delete=models.CASCADE, related_name="addresses")

class Person(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()

urls.py

from django.contrib import admin
from django.conf.urls import include,url
from data.views import PersonViewSet, AddressViewSet
from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'person', PersonViewSet, base_name='person')
router.register(r'address', AddressViewSet, base_name = 'address')

urlpatterns = [
    url(r'^', include(router.urls)),
]

实施例:     url:http://localhost:8000/address
    方法:GET
    param:person_id:0001

此请求需要一个类似的列表     {
        “id”:5,
        “zipcode”:“111”,
        “州”:“FL”,
        “城市”:“迈阿密”,
        “街”:“12”,
        “数字”:111,
        “person_id”:1     }

2 个答案:

答案 0 :(得分:1)

您可以使用detail_route

from rest_framework.decorators import detail_route

class PersonViewSet(viewsets.ModelViewSet):
# You code here

    @detail_route(methods=['get'], )
    def addresses(self, request, pk):
        """
        Show person address.
        """
        person = self.get_object()
        serializer = AddressSerializer(person.addresses, many=True)
        return Response(serializer.data)

现在您可以获取人员地址列表 http://localhost:8000/person/1/addresses

答案 1 :(得分:1)

您可以使用GET参数编写自定义管理器进行过滤。

举个例子,

class AddressQuerySet(models.QuerySet):

    def filter_by_request_params(self, request):

        person_str = request.GET.get('person', None)

        if person_str:
            self = self.filter(person_id=int(person_str.strip()))

        return self

在你的模特中,

class Address(models.Model):
    ......
    ......

    objects = AddressQuerySet.as_manager()

在您的视图中,

class AddressViewSet(viewsets.ModelViewSet):
    ......

    def list(self, request, *args, **kwargs):
        self.queryset = self.queryset.filter_by_request_params(request)
        return super(AddressViewSet, self).list(request, *args, **kwargs)

现在,您可以在QuerySet()方法中添加更多过滤器,并将其用作GET参数,例如http://127.0.0.1:8000/address/?person=1