How to set default value for order field +1 of highest value in Django

Thanks at Advance. I created a model in Django in which it has a title, URL and an order field. Now I have set the default value of this field for the order as ZERO . My requirement is that this defult value should be changed to current highest Ordering number + 1 . Ho, can I do this in the admin interface?

 class FooterLinks(models.Model): title = models.CharField(_("Title"), max_length=200, null = True, blank = True) link = models.CharField(_("Link"), max_length = 200) order = models.IntegerField(_("Sort Order"), default=0) 
+6
source share
2 answers
 from django.db.models import Max new_default = FooterLinks.objects.all().aggregate(Max('order'))['order__max']+1 FooterLinks.objects.filter(order=0).update(order=new_default) 

To make the change permanent, either migrate the database with the South; or how danihp suggested overriding the save method.

However, note that if the table becomes very large, it would be better to implement this logic as a trigger in your database.

Edit:

No, you will run this one time and it will update all records in your database - ideally, you will do this during normal system / window maintenance outages.

To adjust the value in the text box, you need to update the default value specified in your model. Note that default can be either called or called (in other words, a method). Each time a field is displayed, the method will be called.

You can use this to ensure that the default value is always calculated by providing a default method.

+2
source

Inspired by Burkhan's answer, I was able to solve my problem, similar to yours.

So, for your problem: In my models.py create a get_new_default called

 from django.db.models import Max def get_new_default(): new_order_default = FooterLinks.objects.all().aggregate(Max('order'))['order__max']+1 return new_order_default class FooterLinks(models.Model): order = models.CharField(_("Sort Order"), default = get_new_default) 

This inserts a new maximum order value into the text field and keeps the field editable.


--- !! Change !! ---

This causes one problem when resetting the database, as there are no objects to calculate the maximum value. The correction consists in counting all the objects found even if none of them are installed by default: 1:

 from django.db.models import Max def get_new_default(): if FooterLinks.objects.all().count() == 0: new_order_default = 1 else: new_order_default = FooterLinks.objects.all().aggregate(Max('order'))['order__max']+1 return new_order_default class FooterLinks(models.Model): order = models.CharField(_("Sort Order"), default = get_new_default) 
+2
source

Source: https://habr.com/ru/post/923773/


All Articles