Django Model; saving extra items in a ManyToMany field on save
So I am currently implementing a new tagging system for on top of an already existing database.
The current tagging system makes use of a ManyToMany field, however the client would like to have a comma delimited input field (CharField).
开发者_开发百科So I figured best way to do it, without jeopardizing the current architecture is to enable the new comma delimited field, but write away the tags as the previously ManyToMany architecture.
But however i try to do it, the tags get saved into the database tag model, but not on the entry on which they should apply.
Simple rundown:
def save(self, *args, **kwargs):
currTags = self.placeHolderTags.split(",")
for tag in currTags:
dbtag, created = Tag.objects.get_or_create(name=tag)
self.tags.add(dbtag)
super(BeeldBankEntry, self).save(*args, **kwargs)
further model background:
tags = models.ManyToManyField(Tag, verbose_name='Tags', blank=True)
placeHolderTags = models.CharField(max_length=400, verbose_name='Tags2', blank=True)
This is due to django saving m2m fields AFTER model itself. I'm not sure if saving before your code in save() would help, take a look at m2m_changed signal - it looks like just what you need.
精彩评论