Reputation: 1259
I have this simple action I added in my admin.py file.
def groupA(modeladmin, request, queryset):
queryset.update(group=1)
groupA.short_description = "Group A"
//
class StudentAdmin(admin.ModelAdmin):
...
actions = [groupA]
So far everything works as expected.
The problem is that group is a foreign key and it would be more manageable if I could do something like
def groupA(modeladmin, request, queryset):
queryset.update(group="A")
groupA.short_description = "Group A"
I tried with the queryset below but no luck.
queryset.update(group__name="A")
My group model looks like something like that :
class Group(models.Model):
name = models.CharField(max_length=5, default='', blank=True)
....
def __str__(self):
return self.name
So is it possible to do admin actions with the str representation of my Group model ?
Upvotes: 0
Views: 1623
Reputation: 11
I had the same issue and noticed @metraon actually found a nice snippet but it's only in the comments. The snippet worked like a charm for me, even though it's 7 years later now, so I wanted to make it easier to find by posting it as an answer.
Here is the snippet, found at https://djangosnippets.org/snippets/1836/ by metraon:
def create_action(quality):
def action(modeladmin, request, queryset): queryset.update(quality=quality)
name = "mark_%s" % (quality,)
return (name, (action, name, "Mark selected as %s quality" % (quality,)))
class PackageAdmin(admin.ModelAdmin):
list_display = ('name', 'quality')
def get_actions(self, request):
return dict(create_action(q) for q in models.Quality.objects.all())
Upvotes: 1
Reputation: 3777
why don't you import the group model, get the Group A and update all like this?
def groupA(modeladmin, request, queryset):
from models import Group
g = Group.objects.get(name="Group A")
queryset.update(group=g)
Upvotes: 1