I'm trying to apply values from the admin dropdown function (query set). The below code works, but only for Foreign Keys.
If I try to apply this to a many-to-many field, I get a FieldError that says "only non-relations and foreign keys permitted".
def tag_Tagtest(self, request, queryset):
queryset.update(tag=Tag.objects.get(name__iexact='BLAH_BLAH'), updated=timezone.now())
This is my attempt for ManyToMany:
-----models.py
class Product(models.Model):
name = models.CharField ("Name", max_length=400)
tag = models.ManyToMany (Tag, blank=True)
class Tag(models.Model):
name = models.CharField(max_length=30)
tag_type = models.CharField(max_length=30)
def __str__(self):
return self.name
----admin.py
def TEST_M2M (self, request, queryset):
queryset = self.model._meta.app_label, self.model._meta.model_name
How can I use the code above to apply to a many-to-many field?
Django can't add M2M values to multiple objects at once, but you can loop over the queryset.
blahblah=Tag.objects.get(name__iexact='BLAH_BLAH')
for product in queryset:
product.tag.add(blahblah)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.