1
I have these two models to follow:
class Questionario(models.Model):
numero = models.IntegerField()
nome = models.CharField(max_length=300)
class Meta:
db_table = 'questionario'
verbose_name = u'Questionario'
verbose_name_plural = u'Questionarios'
class Pergunta(models.Model):
ask = models.CharField(max_length=200)
questionario = models.ForeignKey(Questionario, related_name='questionario', on_delete=models.CASCADE, null=True)
class Meta:
db_table = 'pergunta'
verbose_name = u'Pergunta'
verbose_name_plural = u'Perguntas'
There is a relationship of 1~N, where for 1 Question one has N Questions. I’m trying to create an update view that will be able to remove the questions if they don’t come on payload.
For example:
{
"id": 1,
"numero": 1,
"nome": "Perfil comportamental e preferência cerebral",
"perguntas": [
{
"id": 1,
"ask": "Eu sou..."
},
{
"id": 2,
"ask": "Eu estou..."
}
]
}
The above object is currently in the bank. I want it when I supply it so:
{
"id": 1,
"numero": 1,
"nome": "Perfil comportamental e preferência cerebral",
"perguntas": [
{
"id": 2,
"ask": "Eu estou..."
}
]
}
the question object with id=1 is removed and only the question object remains with id=2.
This is my current update method:
def update(self, instance, validated_data):
instance.numero = validated_data.get('numero', instance.numero)
instance.nome = validated_data.get('nome', instance.nome)
instance.save()
perguntas = validated_data.get('questionario')
for pergunta in perguntas:
id_pergunta = pergunta.get('id', None)
if id_pergunta:
perguntaBD = Pergunta.objects.get(id=id_pergunta, questionario=instance)
perguntaBD.ask = pergunta.get('ask', perguntaBD.ask)
perguntaBD.save()
else:
pergunta = Pergunta(**pergunta)
pergunta.questionario = instance
pergunta.save()
return instance
Grateful for the help.