简体   繁体   中英

Django 1.8 - How to pre-populate a Model's field based on values in that Model's QuerySet

So I have a simple Model class

Models.py

class Item(models.Model):
    number = models.IntegerField(default=0)
    description = models.CharField(max_length=200)

Upon creating an new Item in the admin, I would like the number field to be pre-populated.

I need it to be pre-populated with an integer that is determined by the last object found with the QuerySet returned with: Item.objects.order_by('number')

So for example; if the highest number in all my Items is 24, I would like the next Item I create via the admin to have a default number of 25.

I know this is a fairly common problem and there are many closely related questions but I'm having real trouble finding an explicit answer for this specific situation.

I'm fairly new to Django so please don't assume any knowledge here.

Thanks in advance.

You can use a callable as your default value . Try this in your models.py:

from django.db.models import Max

def count_numbers():
    max_value = Item.objects.all().aggregate(Max('number'))
    return max_value['number__max'] + 1

class Item(models.Model):
    number = models.IntegerField(default=count_numbers)
    description = models.CharField(max_length=200)

Edit

If you prefer to use the order_by clause, you can use:

def count_numbers():
    query = list(Item.objects.order_by('-number')[:1])
    return query[0] + 1 if query else 0

Not sure which one is faster though.

Try this, you can create a custom ModelAdmin and register it with the admin site:

from django.contrib import admin
from ..models import Item

class ItemAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        # Add custom logic
        largest_item = Item.objects.latest('number')
        obj.number = largest_item.number + 1

        # Delegate default behaviour to superclass
        super(ItemAdmin, self).save_model(request, obj, form, change)

admin.site.register(Item, ItemAdmin)

Possible https://github.com/jpwatts/django-positions app can help in your question?

This module provides PositionField, a model field for Django that allows instances of a model to be sorted by a user-specified position. Conceptually, the field works like a list index: when the position of one item is changed, the positions of other items in the collection are updated in response.

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