Skip to content
Advertisement

not getting fetch data from OneToOneFiled in Django Rest Framework

Models.py- In Hiring Model class Driver field is OneToOneField, how to fetch data from that, i did not find any proper solution how to work with OneToOneField relation, please help me out

class Driver(BaseModel):
    employee_id = models.CharField(max_length=8,unique=True,null=True, default=True)
    city = models.ForeignKey(
        City,
        models.CASCADE,
        verbose_name='City',
        null=True, blank=True
    )
    location = models.ForeignKey(
        Location,
        models.CASCADE,
        verbose_name='Location',
        null=True, blank=True
    )
    city = models.ForeignKey(
    City,
    models.CASCADE,
    verbose_name='City',
    null=True, blank=True
    )
class City(BaseModel):
    name = models.CharField('Name', max_length=80)
    employee_series = models.CharField('Name', max_length=3)
    available_employee_id = models.IntegerField(default=1)

    def __str__(self):
        return self.name
class Location(BaseModel):
    city = models.ForeignKey(
        City,
        models.CASCADE,
        verbose_name='City',
    )
    name = models.CharField('Name', max_length=80)

    def __str__(self):
        return self.name
class Hiring(BaseModel):
    driver = models.OneToOneField(
        Driver,
        models.CASCADE,
        related_name='driver',
        verbose_name='Driver',
        null=True, blank=True
    )
    status = models.CharField(max_length = 255,choices=STATUS_CHOICES, null=True, blank=True)

serializers.py

class CitySerializer(serializers.ModelSerializer):
    class Meta:
        model = City
        fields = ('id', 'name')
class LocationSerializer(serializers.ModelSerializer):
     class Meta:
        model = Location
        fields = ('id', 'name')

class HiringstatusSerializer(serializers.ModelSerializer):
     class Meta:
        model = Hiring
        fields = ('id','driver', 'status')

class DriverEditListSerializer(serializers.ModelSerializer):
    city = CitySerializer(read_only=True)
    location = LocationSerializer()
    hiring=HiringstatusSerializer(many=True, required=False, allow_null=True)
    class Meta:
        model = Driver
        fields=('id','city','location','hiring')

views.py this is views.py render data at frontend

class DriverViewSet(viewsets.ModelViewSet):
    queryset = Driver.objects.filter(is_active=1)
    serializer_class = DriverEditListSerializer
    def get_queryset(self):
        queryset = Driver.objects.filter(is_active=1, 
        city_id=self.request.GET.get('city_id'))
        return queryset

def list_edit_drivers(request):
    driver = Driver.objects.filter(city_id=request.session['global_city_id'])
    context = {
        'menu_hiring': 'active',
        'submenu_driver_edit_list': 'active',
        'driver': driver,
        'city_id': request.session['global_city_id']
    }
    return render(request, 'hiringprocess/list_edit_drivers.html', context=context)

list_edit_drivers.html- html file while ajax calling

var table = $('#drivers').DataTable({
            "pageLength": 100,
            "serverSide": true,
            "bSearchable":true,
            "dom": 'blfrtip',
            "ajax": "/fleet/dt/editdrivers/?format=datatables&city_id={{city_id}}",
            
            "columns": [
                 
                {
                    "data": "uber_name"
                },
                {
                    "data": "mobile"
                },
                {
                    "data": "uber_device_no"
                },
                
                {
                    "data": "location.name"
                },
                {
                    "data": "status"
                },
                {
                    "data": "hiring.status"
                },
                
                
        });
    });

output errorwhile added some hiring.status column in fornt end error

    ERROR Internal Server Error: /fleet/dt/editdrivers/
Traceback (most recent call last):
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesdjangocorehandlersexception.py", line 34, in inner   
    response = get_response(request)
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesdjangocorehandlersbase.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesdjangocorehandlersbase.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesdjangoviewsdecoratorscsrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesrest_frameworkviewsets.py", line 125, in view
    return self.dispatch(request, *args, **kwargs)
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesdjangoutilsdecorators.py", line 45, in _wrapper       
    return bound_method(*args, **kwargs)
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesdjangocontribauthdecorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesrest_frameworkviews.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesrest_frameworkviews.py", line 469, in handle_exception 
    self.raise_uncaught_exception(exc)
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesrest_frameworkviews.py", line 480, in raise_uncaught_exception
    raise exc
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesrest_frameworkviews.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesrest_frameworkmixins.py", line 38, in list
    queryset = self.filter_queryset(self.get_queryset())
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesrest_frameworkgenerics.py", line 150, in filter_queryset
    queryset = backend().filter_queryset(self.request, queryset, self)
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesrest_framework_datatablesfilters.py", line 186, in filter_queryset
    queryset = queryset.filter(q).distinct()
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesdjangodbmodelsquery.py", line 892, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesdjangodbmodelsquery.py", line 910, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesdjangodbmodelssqlquery.py", line 1290, in add_q     
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesdjangodbmodelssqlquery.py", line 1312, in _add_q    
    current_negated, allow_joins, split_subq)
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesdjangodbmodelssqlquery.py", line 1318, in _add_q    
    split_subq=split_subq, simple_col=simple_col,
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesdjangodbmodelssqlquery.py", line 1190, in build_filter
    lookups, parts, reffed_expression = self.solve_lookup_type(arg)
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesdjangodbmodelssqlquery.py", line 1049, in solve_lookup_type
    _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
  File "E:10dec_everestfleeteverest_jarvisenvlibsite-packagesdjangodbmodelssqlquery.py", line 1420, in names_to_path
    "Choices are: %s" % (name, ", ".join(available)))
django.core.exceptions.FieldError: Cannot resolve keyword 'hiring' into field. Choices are: aadhar, aadhar_back, aadhar_no, aadhar_verification, admission_form_status, alternate_number, appuser, bank_account_no, bank_holder_name, bank_name, bank_passbook, bill, carsnotdriven, carstatus, city, city_id, created_at, created_by, created_by_id, dailytrip, date_of_exit, date_of_joining, dl_extract, driver, driver_city, driverchangelog, driverpenalty, driverstatus, duty, employee_id, employer, 
employer_id, essentialservicetravel, form_complete_status, fuelbill, id, ifsc_code, is_active, is_deleted, ledger, ledger_balance, ledger_balance_prev, ledger_balance_week, ledger_balance_week_prev, license, license_expiry_date, license_issue_date, license_no, location, location_id, mobile, name, pan, pan_no, payment_type, payout, permanent_address, photo, present_address, reference, remark, rent_agreement, salary_plan, shift, shift1, shift1_driver, shift2, shift2_driver, shiftreport, source, status, sw_pass, training_status, trip, type, uber_device_no, uber_name, uber_uuid, updated_at, updated_by, updated_by_id, vista_password, vista_username, weeklydata
ERROR "GET /fleet/dt/editdrivers/?format=datatables&city_id=1&draw=2&columns%5B0%5D%5Bdata%5D=employee_id&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=uber_name&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=mobile&columns%5B2%5D%5Bname%5D=&columns%5B2%5D%5Bsearchable%5D=true&columns%5B2%5D%5Borderable%5D=true&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B3%5D%5Bdata%5D=uber_device_no&columns%5B3%5D%5Bname%5D=&columns%5B3%5D%5Bsearchable%5D=true&columns%5B3%5D%5Borderable%5D=true&columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B3%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B4%5D%5Bdata%5D=aadhar_no&columns%5B4%5D%5Bname%5D=&columns%5B4%5D%5Bsearchable%5D=true&columns%5B4%5D%5Borderable%5D=true&columns%5B4%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B4%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B5%5D%5Bdata%5D=location.name&columns%5B5%5D%5Bname%5D=&columns%5B5%5D%5Bsearchable%5D=true&columns%5B5%5D%5Borderable%5D=true&columns%5B5%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B5%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B6%5D%5Bdata%5D=status&columns%5B6%5D%5Bname%5D=&columns%5B6%5D%5Bsearchable%5D=true&columns%5B6%5D%5Borderable%5D=true&columns%5B6%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B6%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B7%5D%5Bdata%5D=hiring.status&columns%5B7%5D%5Bname%5D=&columns%5B7%5D%5Bsearchable%5D=true&columns%5B7%5D%5Borderable%5D=true&columns%5B7%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B7%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B8%5D%5Bdata%5D=id&columns%5B8%5D%5Bname%5D=&columns%5B8%5D%5Bsearchable%5D=true&columns%5B8%5D%5Borderable%5D=false&columns%5B8%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B8%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D%5Bdir%5D=asc&start=0&length=100&search%5Bvalue%5D=Training+Completed%09&search%5Bregex%5D=false&_=1641204802582 HTTP/1.1" 500 30874

Advertisement

Answer

Changes related and verbose name solve this problem:

class Hiring(BaseModel):
    driver = models.OneToOneField(
        Driver,
        models.CASCADE,
        related_name='hiring',
        verbose_name='hiring',
        null=True, blank=True
    )
    status = models.CharField(max_length = 255,choices=STATUS_CHOICES, null=True, blank=True)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement