python/django: model object has no attribute 'prefetch_related'

青春壹個敷衍的年華 提交于 2021-01-03 06:50:25

问题


I have created a model 'VehicleDetails' in which a user can fill the details of a vehicle and another model 'TripStatus' in which he updates the vehicle location. I wanted to get the latest location for which i did as in my below code. I use prefetch_related in my view to returns the location values for a particular vehicle. But, when after running the server, it raises an error : "TripStatus object has no attribute 'prefetch_related'". I would appreciate helping me solve this. models.py:

class VehicleDetails(models.Model):
    Vehicle_No = models.CharField(max_length=20)

class TripStatus(models.Model):
    vehicledetails = models.ForeignKey(VehicleDetails, related_name='statuses')
    CHOICES = (('Yet to start', 'Yet to start'),('Trip starts', 'Trip starts'), ('Chennai','Chennai'), ('Vizag', 'Vizag'), ('Kolkata', 'Kolkata'))
    Vehicle_Status = models.CharField(choices=CHOICES, default="Yet to start", max_length=20)
    statustime = models.DateTimeField(auto_now=False, auto_now_add=True)

views.py:

def status(request):
    tripstatus = TripStatus.objects.all().latest('statustime').prefetch_related('statuses')
    context = {
        "tripstatus": tripstatus,
    }
    return render(request, 'loggedin_load/active_deals.html', context)

template:

{% for status in vehicledetails.statuses.all %}
{{status.Vehicle_Status}}
{% endfor %}

回答1:


prefetch_related works on a queryset object. Latest returns a single model not a queryset.

This should work :

tripstatus = TripStatus.objects.all().prefetch_related('statuses').latest('statustime')


来源:https://stackoverflow.com/questions/39818121/python-django-model-object-has-no-attribute-prefetch-related

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!