How to update "deleting" objects from a nested object?

Asked

Viewed 27 times

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.

1 answer

0

def update_instance_from_dict(instance, attrs, save=False):
    for attr, val in attrs.items():
        setattr(instance, attr, val)
    if save:
        instance.save()
    return instance


def update(self, instance, validated_data):
    pergunta_data = validated_data.pop('pergunta', [])
    
    update_instance_from_dict(instance, validated_data, save=True)

    instance.pergunta.all().delete()

    for itens in pergunta_data:
        Pergunta.objects.create(
            questionario=instance,
            **itens
        )

    return instance

Browser other questions tagged

You are not signed in. Login or sign up in order to post.