简体   繁体   中英

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

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 %}

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM