Good morning my friends.
Before sending this doubt I searched a lot in the forums of life!

I have the following code that does bulk inclusion:

def seach_create(request):
    template_name = 'seach_create.html'
    if request.method == 'POST':
        form = SearchForm(request.POST)
        if form.is_valid():
            data = dict(
                search_key=form.cleaned_data['search_key'],
                person=form.cleaned_data['person'],
                researched=form.cleaned_data['researched'],
                questions=Question.objects.all(),
            )
            #criar_pesquisa(**data)
            addQuestions(**data)
            # Não usar o método save().
            # form.save()
            return redirect('core:seach_create')
    else:
        form = SearchForm()
    context = {'form': form}
    return render(request, template_name, context)


def addQuestions(**data):
    #person = Person.objects.get(pk=1)
    questions = Search.objects.all()

    for question in questions:
        try:
            Search.objects.get(
                search_key=data['search_key'],
                person=data['person'],
                researched=data['researched'],
                question=question
            )
            print('existe')
        except Search.DoesNotExist:
            for question in questions:
                Search.objects.get_or_create(
                    search_key=data['search_key'],
                    person=data['person'],
                    researched=data['researched'],
                    question=question
                )
            print('Não existe')

    return HttpResponseRedirect('/')




The problem is precisely this, if the registry already exists it should 
ignore or edit the existing data, however I'm getting the error mentioned 
in this post.

Where can I fix this problem?

Below I will put the models used in this project:

class Person(models.Model):
    cdalterdata = models.IntegerField('Cód. Alterdata', db_index=True)
    name = models.CharField('Nome', max_length=100)
    #email = models.EmailField(null=True, blank=True)
    phone = models.CharField('Telefone', max_length=11, null=True, blank=True)

    class Meta:
        ordering = ('name',)
        verbose_name = 'Pessoa'
        verbose_name_plural = 'Pessoas'

    def __str__(self):
        return self.name

    def to_dict_json(self):
        return {
            'cdalterdata': self.cdalterdata,
            'name': self.name,
            'email': self.email,
            'phone': self.phone,
            # 'gender': self.get_gender_display(),
        }

    # def get_absolute_url(self):
    #     return reverse('pesquisa_alter:add_pesquisa', args=[str(self.id)])


class Client(Person):
    last_search = models.CharField('Última pesquisa.', max_length=11, 
null=True, blank=True)
    created_on = models.DateField(
        'Criado em.',
        auto_now_add=True,
        auto_now=False
    )


    class Meta:
        ordering = ('name',)
        verbose_name = 'Cliente'
        verbose_name_plural = 'Clientes'

    def get_absolute_url(self):
        return reverse('person_client_detail', args=[str(self.pk)])


class Question(models.Model):
    LEVEL_CHOICES = (
        ('0', 'Indefinido'),
        ('1', 'Dependencia'),
        ('2', 'Confianca'),
        ('3', 'Comprometimento'),
        ('4', 'Preditiva'),
    )
    question = models.CharField('Pergunta', max_length=200)
    level = models.CharField('Nível', max_length=15,
                             choices=LEVEL_CHOICES, default='0')

    class Meta:
        verbose_name = 'Questão'
        verbose_name_plural = 'Questões'
        ordering = ('-level',)

    def __str__(self):
        return self.question


class SearchManager(models.Manager):

    def add_question(self, search_key, person, researched, question):
        search, created = self.get_or_create(
            search_key=search_key, person=person, researched=researched, 
question=question)
        if not created:
            search.search_key = search.search_key
            search.person = search.person
            search.question = search.question
            search.researched = search.researched
            search.save()
        return search


class Search(models.Model):
    RESPONSE_CHOICES = (
        ('V', 'Verdadeiro'),
        ('F', 'Falso'),
        ('I', 'Indefinido'),
    )
    search_key = models.CharField(
        'Chave da pesquisa', max_length=200, db_index=False)
    person = models.ForeignKey(
        'core.client', related_name='Cliente', on_delete=models.CASCADE)
    researched = models.CharField('Entrevistado', max_length=200)
    question = models.ForeignKey(
        'core.question', related_name='Pergunta', on_delete=models.CASCADE,)
    response = models.CharField(
        'Resposta', max_length=1, choices=RESPONSE_CHOICES, default='I')
    participation_on = models.DateField(
        'período da pesquisa',
        auto_now_add=True,
        auto_now=False
    )
    created_on = models.DateTimeField(
        'solicitado em',
        auto_now_add=True,
        auto_now=False
    )

    #objects = SearchManager()

    class Meta:
        verbose_name = 'Pesquisa'
        verbose_name_plural = 'Pesquisas'
        unique_together = (('search_key', 'person', 'question'),)
        ordering = ('-participation_on',)

    def __str__(self):
        return self.question.question



-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/92b6809a-3bd1-40db-aecd-87cadf077bb5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to