Admin action- queryset to apply Many to Many

2019-09-12 08:18发布

问题:

How do I use the admin action to create a queryset which will apply a Many-to-Many value?

I understand the 'value' will have to already exist (in my case, the colour itsel will have to exist).

Models

class Colours(models.Model):
    colour_name = models.CharField(max_length=50)

class Car(models.Model):
    brand = models.CharField(max_length=200)
    available_colours = models.ManyToManyField(Colours, blank=True)

Admin.py

class CarAdmin(admin.ModelAdmin):
    actions = ['Red']

Attempt 1: only works for FK

def Red(self, request, queryset):
        queryset.update(colour=Colour.objects.get(colour_name__iexact='Red'), updated=timezone.now())

Attempt 2: Did not work

def Red(self, request, queryset):
    queryset.update = self.model._meta.app_label, self.model._meta.model_name

回答1:

you can assign relations sets in django.

def Red(self, request, queryset):
    red_color = Colour.objects.get(colour_name__iexact='Red')
    queryset.update(available_colours=[red_color])

according to your comment and to docs, it seems django doesnot support bulk update for manytomany fields.

you can solve it this way:

def Red(self, request, queryset):
    red_color = Colour.objects.get(colour_name__iexact='Red')
    for car in queryset:
        car.available_colours.add(red_color)