Admin action- queryset to apply Many to Many

最后都变了- 提交于 2019-12-12 03:25:23

问题


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)


来源:https://stackoverflow.com/questions/33642949/admin-action-queryset-to-apply-many-to-many

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!