python 2.7 - Adding ManyToMany related object on the fly in django -


let's have 2 models those:

class property(models.model):     name= models.charfield('property name', max_length=200)     slug = models.charfield(max_length=200)      def save(self, *args, **kwargs):         if not self.id:             self.slug= slugify(self.name)         super(tag, self).save(*args, **kwargs)   class thing(models.model):     name = models.charfield('name',max_length=200)     description = models.textfield('description')     pub_date = models.datetimefield('pub date',default=datetime.now())     properties = models.manytomanyfield(property, blank=true) 

when create new thing, i'd able create new related properties, if don't exist.

like, on ipotetically "thingform.save()", want iterate through properties selected, create ones not exist , link them new thing

how can achieve this?

this how can create new properties , link them thing afterwards:

# assuming have list of names of selected properties selected_properties = ['name_1', 'name_2']  prop_name in selected_properties:     property, created = property.objects.get_or_create(name=prop_name)     # assuming have thing instance (thing) attach properties ...     thing.properties.add(property) 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -