Is there a way to create a Django model instance which has automatic primary key generation without passing named arguments?
I'm trying to create a generic function in Django, creating a bunch of model instances by calling an evaluated model constructor. I.e. I pass in a string model = "Model"
which corresponds to an actual model in my database. Then I call Model = getattr(mymodule, model)
to get the constructor for that model. Now I can call Model(list, of, arguments)
. These arguments will of course vary with the different models being passed in, but this is no problem as long as some field in my model is marked as primary_key=True
. But when the model has an auto-generated id, the constructor will try to pass the first argument (in my case) to the id field, and it all falls apart and I get something like ValueError: Field 'id' expected a number but got 'some_string'
.
I found that one solution to this problem was passing named arguments, but I think this will make my code very elaborate since I'm trying to keep it generic for all my models. Another possibility is to pass in None
as my first argument, and it works, but I think it is a wonky solution.
Is there a way to create a model instance with automatic primary key generation without passing named arguments? Can I have the id of the model not be a part of the constructor?