1👍
Uhm, you have to specify what you mean by “it does not work”. Theoretically it does work – you can indeed create objects by calling RandomClass.objects.create(field1='field-1-value', field2='field-2-value')
and it works. If it does “work” for .get()
and doesn’t “work” for .create()
(I assume you get some kind of an exception when trying that code), then one reason could be that get()
retrieves and existing object from the DB and can fill all the required field values from the DB, while .create()
inserts a new object into the DB and if some required values are missing, then you get an exception.
An alternative or a solution for that is not to use create()
that is a direct DB command basically, but to use the Django intermediary model instance for creating an object. Basically the difference is as follows:
from django.db import models
class RandomModel(models.Model):
# NB! Required fields
field1 = models.CharField(max_length=32)
field2 = models.CharField(max_length=32)
# This is how you want to do it
RandomModel.objects.create(field1='value')
# An error is returned because you didn't specify a value for field2 and this goes directly to DB
# An alternative:
obj = RandomModel(field1='value')
obj.field2 = 'value232'
obj.save() # Only here is it saved to the DB
If you’re looking for a more concrete answer, update your question accordingly.
EDIT:
Because the field question
is in another model and you CAN NOT change another model’s fields using the create()
method of one model. However, you can filter existing objects based on their field values, using methods like .get()
, .filter()
, .exclude()
.
To achieve what you want, you have to do the following (not the only way, mind you):
# if the question instance exists and you just want to change the question (kind of unlikely in my opinion?)
question_instance = QuestionModel.objects.get(#some-params-that-get-the-question)
question_instance.question = 'How the hell did we end up here?'
question_instance = question_instance.save()
# Proceed to create the other model
# if the question instance does not exist (more likely version)
question = QuestionModel.objects.create(question='Is this more like it?')
answer = AnswerModel.objects.create(answer='Yes, it is.', question=question)