[Django]-How do I add a temporary field to a model in Django?


You can define a foreign key to non-materialized django model which stores the info you require.

To do so, in the new model to which foreign key (or a OnetoOne Key) is defined, just place

class _meta:
    managed = False


I’m not sure exactly what you’re trying to do. But remember that Django models are just Python objects – and Python objects are completely dynamic. So it is perfectly valid to do obj.uuid = whatever even if there is no uuid field defined on the model.


I don’t know of such a temporary field. It would be nice 🙂

But my suggestion is this: In the view that receives the JSON and makes it into objects, you check the attributes. You create an object, with only the “real” attributes (not foreign keys or M2M). You can assign arbitrary attributes to them (instance.arbitrary_attribute = something) but you won’t get the nice lookup mechanism (Model.objects.filter(…)). After you created all the objects, you loop over the objects again, and for each FK you look up the object that has the link’s UUID, and link to it (using the instance.id).


You can try creating plain python attributes, they are not saved to db. Like:

class Link(models.Model):
    sourceuuid = None


Why not just use UIDS as primary keys ?

set primary_key to True

class Node(models.Model):
    uuid = models.CharField(max_length=32, primary_key=True)

class Link(models.Model):
    uuid = models.CharField(max_length=32, primary_key=True)

Leave a comment