Create rest api in django-rest-framework with relation
create rest api in django-rest-framework
I have 2 tables
Key table: User
id | PK
Name | varchar(255)
Second table: address
id | PK
address | varchar(255)
city_id | int
user_id | FK
Now when I click on the request for the user I also need the user's Json address
Like this
[
{
"id": 98,
"name": "rijoj@selectsourceintl.com",
"address": [
{
"id": 51,
"city_id": 5,
"addrss": "New York",
},
{
"id": 61,
"city_id": 5,
"addrss": "California",
},
]
}
]
+3
source to share
1 answer
models.py -
class User(models.Model):
catcher_fname = models.CharField(max_length = 128, blank = True)
catcher_lname = models.CharField(max_length = 128, blank = True)
api_key = models.CharField(max_length = 100, blank = False)
class Address (models.Model):
address = models.CharField(max_length = 150)
city = models.CharField(max_length = 255)
user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='addresses')
Note. The id field is auto-incrementing and built-in in django, you don't need to specify it directly. Below is a demo of how you should bind user obj and address obj.
>> from .models import User,Address
>> user_obj = User.objects.get(pk=pk)
>> address_obj = Address.objects.get(pk=address_pk)
>> user_obj.address = address_obj
>> user_obj.save()
Later, you can access the address from a custom object as -
>> from .models import User
>> user_obj = User.objects.get(pk=pk)
>> user_obj.addresses.all() (will give the data)
Now install django-restframework
views.py -
from rest_framework.generics import RetrieveAPIView
from .serializers import UserDetailSerializer
class UserAPIView(RetrieveAPIView):
serializer_class = UserDetailSerializer
lookup_field = 'id'
queryset = User.objects.all()
serializers.py -
from .models import User,Address
from rest_framework import serializers
class AddressSerializer(serializers.ModelSerializer):
class Meta:
model = Address
fields = ('id', 'city_id', 'address')
class UserDetailSerializer(serializers.ModelSerializer):
address = AddressSerializer(many=True)
class Meta:
model = User
fields = (
'id',
'name',
'address'
)
urls.py
from django.conf.urls import url
from reports.views import UserAPIView
urlpatterns = [
url(r'^users/(?P<id>[0-9]+)/$',UserAPIView.as_view(), name= 'users'),
]
+2
source to share