0

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
Yian
  • 189
  • 14
  • what do you want to do exactly? – doniyor Nov 11 '15 at 03:35
  • Use an admin action (dropdown menu), apply an m2m relations (in this case, the colour "RED") to a ticked object. Similar what you can do with django Admin to "delete" multiple objects, I'd like to use that area to add my this custom action. – Yian Nov 11 '15 at 03:42
  • so you want to make all cars red which are ticked? – doniyor Nov 11 '15 at 05:09
  • Exactly. Apply it to all the models ticked. If the car is already "RED" it can ignore it – Yian Nov 11 '15 at 06:01

1 Answers1

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)
doniyor
  • 36,596
  • 57
  • 175
  • 260
  • This says "Cannot update model field (only non-relations and foreign keys permitted).". This is basically my example from above. Here's the traceback (note, I'm using Category where my example wanted colour) http://dpaste.com/3QJE6JV – Yian Nov 12 '15 at 00:53
  • ah, then bulk update doesnot support this. I will update my answer – doniyor Nov 12 '15 at 03:44
  • Almost! This works, but removes any M2M's that already exist (ie removes all other colours that relate to car I add "red" to). How is this fixed? – Yian Nov 12 '15 at 06:41
  • Thank you. What will happen if I try to apply the colour, and a car already has that colour relation? will it add it twice or ignore? – Yian Nov 12 '15 at 22:09
  • @yian you can assign multiple times. Not sure if it ignores but supposed to. Please try it and let me know – doniyor Nov 13 '15 at 06:25
  • I dont want it to assign it multiple times. I want it to ignore adding the value if it already exists. – Yian Nov 15 '15 at 02:37