Access to the last object of model inside model itself

23 views
Skip to first unread message

Mohammad Etemaddar

unread,
Jan 25, 2019, 12:27:46 PM1/25/19
to Django users
Hello
I need the last object of model inside it.
for example I have:
class Field(models.Model):
category = models.ForeignKey(Category, related_name='fields', on_delete=models.CASCADE,
default = get_last_factory_field_category())

def get_last_factory_field_category():
return Field.objects.last().category

In this definition, will get not defined error. because the function is defined after model.

preivously, I used lambda to get access to the last category. But makemigrations did not work while using lambda.

The clear problem is getting access to the last object of model inside of it.

Jason

unread,
Jan 25, 2019, 2:02:43 PM1/25/19
to Django users
This really should be in a custom model manager, and not the model itself.

Mohammad Etemaddar

unread,
Jan 26, 2019, 12:15:44 PM1/26/19
to Django users
Im not agree. Managers are created for custom query. But here the query is last.
I think I got the philosophy. The default value should not be a manager, because the database does not understand it.
Maybe I am wrong!

Mohammad Etemaddar

unread,
Jan 26, 2019, 12:17:30 PM1/26/19
to Django users
I commented out the default value and then ran the makemigrations again, and then uncommented again and worked. Of course by lambda.
Reply all
Reply to author
Forward
0 new messages