返回Django REST框架中的最后一个对象

y4ekin9u  于 2023-10-21  发布在  Go
关注(0)|答案(2)|浏览(100)

我刚开始在StackOverflow和Django上提问,所以如果我犯了任何错误,我很抱歉。
到目前为止,我有一个基本的API与Django和REST框架。我只想返回添加到数据库的最后一个对象,这可以用最高的ID来完成。
这是models.py:

from django.db import models

class Humidity(models.Model):
    value = models.FloatField()

class Temperature(models.Model):
    value = models.FloatField()
    isFarenheit = models.BooleanField()

我没有任何时间字段,但如果需要,我可以添加它们。
这是serializers.py:

class HumiditySerializer(serializers.ModelSerializer):
    class Meta:
        model = Humidity
        fields = ('id', 'value')

class TemperatureSerializer(serializers.ModelSerializer):
    class Meta:
        model = Temperature
        fields = ('id', 'value', 'isFarenheit')

这是views.py:

from django.shortcuts import render
from rest_framework import viewsets, permissions
from .models import Humidity, Temperature
from .serializers import HumiditySerializer, TemperatureSerializer

class HumidityView(viewsets.ModelViewSet):
    queryset = Humidity.objects.order_by('-id')[0]
    serializer_class = HumiditySerializer

class TemperatureView(viewsets.ModelViewSet):
    queryset = Temperature.objects.order_by('-id')[0]
    serializer_class = TemperatureSerializer

这是错误的追溯:

Traceback (most recent call last):
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner
    self.run()
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 390, in check
    include_deployment_checks=include_deployment_checks,
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 377, in _run_checks
    return checks.run_checks(**kwargs)
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
    return check_method()
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 398, in check
    for pattern in self.url_patterns:
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 80, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 579, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 80, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 572, in urlconf_module
    return import_module(self.urlconf_name)
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\usuario\Desktop\Subcarpetas\iot-sensors\iot-sensors-backend\iot-sensors-backend\iotSensors\iotSensors\urls.py", line 21, in <module>
    path('', include('api.urls')),
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\usuario\Desktop\Subcarpetas\iot-sensors\iot-sensors-backend\iot-sensors-backend\iotSensors\api\urls.py", line 6, in <module>
    router.register('humidity', views.HumidityView)
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\rest_framework\routers.py", line 75, in register
    basename = self.get_default_basename(viewset)
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\rest_framework\routers.py", line 162, in get_default_basename
    return queryset.model._meta.object_name.lower()
AttributeError: 'Humidity' object has no attribute 'model'

只有当我在views.py中将Humidity.objects.all()更改为Humidity.objects.order_by('-id')[0]时才会抛出此错误,温度也是如此。
如何返回上次保存的对象?

n3h0vuf2

n3h0vuf21#

由于model中没有timedate字段,因此只能通过id检索最新的对象。

Humidity.objects.all().order_by('-id')[:1]

-idreverse 顺序检索对象。由于djangoQueryDict对象是延迟加载的,因此这将只检索最新的值。
可以使用last函数检索最新的对象

Humidity.objects.all().latest()

或者只检索具有最新id的对象,

Humidity.objects.latest('id')
inkz8wg9

inkz8wg92#

# To get last object or record

Humidity.objects.last()

相关问题