Django: creating links in memory without saving to DB

I have some models with such relationships:

class Item(model.Model): name = models.CharField() class Group(models.Model): item = models.ManyToManyField(Item) class Serie(models.Model): name = models.CharField() chart = models.ForeignKey(Chart) group = models.ForeignKey(Group) class Chart(models.Model): name = models.CharField() 

I need to create a Chart object on the fly, without saving to the database. But I cannot do this, because Django is trying to use the primary keys of the objects when assigning relationships.

I just want Group.add(Item()) work without having to save objects in the database.

Is there any easy way?

+4
source share
2 answers

Revival here for future readers:

I circumvented this use case by specifying a private attribute that represents the relationship within the classes and property to check if the object can be retrieved from the database or is in memory.

Here is a simple example:

 class Parent(models.Model): _children = [] name = models.CharField(max_length=100) @property def children(self): if _children: return self._children else: return self.children_set.all() def set_virtual_children(self, value): # could use a setter for children self._children = value # Expose _children to modification def some_on_the_fly_operation(self): print(','.join([c.name for c in self.children])) class Children(models.Model): parent = models.ForeignKey(Parent) name = models.CharField(max_length=100) 

That way I can install "virtual children" and use all the specific methods on the fly

+3
source

EDIT: It seems that the approach described here is not enough for django to add to the ManyToMany relationship.

You tried to add primary_key=True and unique=True to the name attribute of the Item model. Then executing Group.add(Item("item_name_here")) should work if you have the opportunity to create a name on the fly.

I have not tested it, but I think your path failed because add() wants to use the primary key, which by default is the identifier of the auto-increment that is assigned when it is stored in the database.

0
source

All Articles