Era Era - 1 year ago 202
Python Question

'ReverseManyToOneDescriptor' object has no attribute 'latest'

I have received this error when trying to run a function. This is my first django/python project so I am not experienced in this. I have searched for this error but not found anything similar.

def getpriority(chunks):
p = 0
for chunk in chunks:
a = chunk.result_set.all()
l = a.latest()
if pytz.utc.localize( - l.timestamp > datetime.timedelta(days=3):
x = getresult(chunk)

I am trying to assign priorities to my Chunk model so I can select the Chunk with the highest priority to use the object.

I believe that my error is in calling latest() on 'a'.

When I run Chunk.result_set.latest() in a django shell I get the following error:

Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'ReverseManyToOneDescriptor' object has no attribute 'latest'

In my Result model, I have set get_latest_by which I believe is required to run .latest():

class Result(models.Model):
rel_chunk = models.ForeignKey(Chunk, on_delete=models.CASCADE)
score = models.IntegerField()
timestamp = models.DateTimeField(auto_now_add=True)

class Meta:
get_latest_by = 'timestamp'

I believe that the error lies in the fact that I'm calling latest on a related object set but if this can't be called on a related object set then how can I find the latest related Result?

Answer Source

It should be Chunk.result_set.all().latest() not Chunk.result_set.latest()

result_set is a ReverseManyToOneDescriptor not a queryset and latest() method is only for querysets. In order to get a queryset, apply .all() to it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download