Order Model Admin?

With the Django admin interface, how do you guarantee that the objects in the html select multiple are sorted in some order (prefer the alphabet)? The problem is that I have 3 models - CD, Song, Singer. One CD admin control panel, the song is built into the CD, and Singer is a multi-headed field that I would like to sort out!

Here is my code:

model.py

class CD(models.Model): cd_name = models.CharField("CD Name",max_length=50) date = models.DateField("CD Release Date") photo = models.ImageField("CD Cover",blank=True,upload_to='covers') singers = models.ManyToManyField(Singer,blank=True,null=True) def __unicode__(self): return self.cd_name class Song(models.Model): cid = models.ForeignKey(CD) track_num = models.PositiveIntegerField("Track Number",max_length=2) song_name = models.CharField("Song Name",max_length=50) soloists = models.ManyToManyField(Singer,blank=True,null=True) stream_url = models.URLField("Stream URL", blank=True) def __unicode__(self): return self.song_name class Singer(models.Model): (not relevent) 

admin.py

 class SongInline(admin.TabularInline): model = Song extra = 0 class CDAdmin(admin.ModelAdmin): list_display = ('cd_name', 'date') inlines = [ SongInline, ] admin.site.register(CD, CDAdmin) 
+6
source share
1 answer

formfield_for_manytomany

 class SongInline(admin.TabularInline): model = Song extra = 0 def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "soloists": kwargs["queryset"] = Singer.objects.order_by('last_name') return super(SongInline, self).formfield_for_manytomany(db_field, request, **kwargs) 

This answers your specific "OrderAdmin Ordering" question, but in your case, you can simply define the default order for your m2m model using the meta class model of the ordering model.

http://docs.djangoproject.com/en/dev/ref/models/options/#ordering

 class Singer(models.Model): # my model class Meta: ordering = ['name'] # your select box will respect this as well. 
+2
source

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


All Articles