Home > front end >  Django REST framework on primary key
Django REST framework on primary key

Time:10-04

I am currently trying to display multiple models with a primary key to find that specific data but I am encountering the following error: selected() got an unexpected keyword argument 'pk'

Here is the code:

views.py

from rest_framework.response import Response
from rest_framework.decorators import api_view
from .serializers import DeviceSerializers, DeviceDetailSerializers
@api_view(['GET'])
def selected(request,pk):
    devices = Device.objects.all(pk=pk)
    devicedetail = DeviceDetail.objects.all(DD2DKEY=pk)
    devserializer = DeviceSerializers(devices, many = True)
    devdserializer = DeviceDetailSerializers(devicedetail, many = True)
    results = devserializer.data   devdserializer.data
    return Response(results)

serializers.py

from rest_framework import serializers
from .models import Device, DeviceDetail

class DeviceSerializers(serializers.ModelSerializer):
    class Meta:
        model=Device
        fields = '__all__'

class DeviceDetailSerializers(serializers.ModelSerializer):
    class Meta:
        model = DeviceDetail
        fields = '__all__'

models.py

class Device(models.Model):
    hostname = models.CharField(max_length=50, unique = True)
    ipaddr = models.GenericIPAddressField(protocol='ipv4', unique=True, verbose_name='mangement IP') ##Use for mgt_id_addr
    date_added = models.DateTimeField(default=timezone.now)
    

    def __str__(self):
        return self.hostname

class DeviceDetail(models.Model):
    
    SUBNET_CHOICES = (
    ('16','16'),
    ('17', '17'),
    ('18','18'),
    ('19','19'),
    ('20','20'),
    ('21', '21'),
    ('22', '22'),
    ('23', '23'),
    ('24', '24'),
    ('25', '25'),
    ('26', '26'),
    ('27', '27'),
    ('28', '28'),
    ('29', '29'),
    ('30', '30'),
    )

    DEV_MODS =(
        ('Catalyst 9606R', 'Catalyst 9606R'),
        ('C9300L-48T-4X', 'C9300L-48T-4X')
    )

    
    mgt_interface = models.CharField(max_length=50)
    subnetmask = models.CharField(max_length=2, choices = SUBNET_CHOICES)
    ssh_id = models.CharField(max_length=50)
    ssh_pwd = models.CharField(max_length=50)
    enable_secret = models.CharField(max_length=50)
    dev_mod=models.CharField(max_length=50, choices = DEV_MODS) ##device_model replacement
    DD2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link up the tables
    
    def __str__(self):
        return self.hostname

urls.py (In app)

from django.urls import path
from .views import DeviceListView
from . import views
from .views import devicelist
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
    
    path('selecteddevice/<int:pk>', views.selected),
]

Is passing a primary key not allowed for the Django Rest framework? I coded the views with the knowledge of coding for the views for the HTML pages but it does not seem to work. For the URL, i typed 127.0.0.1/selecteddevice/179 for example. My database has the record of 179

Traceback in my powershell:

Traceback (most recent call last):
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
    raise exc
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\rest_framework\decorators.py", line 50, in handler
    return func(*args, **kwargs)
TypeError: selected() got an unexpected keyword argument 'pk'

CodePudding user response:

Not an expert but You can try this:

from rest_framework.response import Response
from rest_framework.decorators import api_view
from .serializers import DeviceSerializers, DeviceDetailSerializers
@api_view(['GET'])
def selected(request,pk=None):
    if pk != None:
        devices = Device.objects.filter(id=pk)
        print(devices)
        devicedetail = DeviceDetail.objects.filter(DD2DKEY=pk)

        devserializer = DeviceSerializers(devices, many=True)
        devdserializer = DeviceDetailSerializers(devicedetail, many=True)
        results = {
            "dev":devserializer.data,
            "devd" : devdserializer.data,
        }
        # results = devserializer.data   devdserializer.data
        return Response(results)
  • Related