Created
October 5, 2018 01:01
-
-
Save CoutinhoElias/3d7f25cf4bc7a5ff8c5009e57bd2c23f to your computer and use it in GitHub Desktop.
Problema com Bulkcreate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Modelos | |
class Questions(models.Model): | |
LEVEL_CHOICES = ( | |
('0', 'Indefinido'), | |
('1', 'Dependencia'), | |
('2', 'Confianca'), | |
('3', 'Comprometimento'), | |
('4', 'Preditiva'), | |
('5', 'Comprometimento'), | |
) | |
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 PesquisaManager(models.Manager): | |
def add_question(self, search_key, question): | |
pesquisa, created = self.get_orcreate(search_key=search_key, question=question) | |
if created: | |
pesquisa.save() | |
return pesquisa | |
class Pesquisa(models.Model): | |
RESPOSTA_CHOICES = ( | |
('V', 'Verdadeiro'), | |
('F', 'Falso'), | |
('I', 'Indefinido'), | |
) | |
search_key = models.CharField('Chave da pesquisa', max_length=10, db_index=True) | |
person = models.ForeignKey('person.person', related_name='Pessoa', on_delete=models.CASCADE) | |
question = models.ForeignKey('bolsa.Questions', related_name='Pergunta', on_delete=models.CASCADE,) | |
response = models.CharField('Resposta', max_length=1, choices=RESPOSTA_CHOICES, default='I') | |
participation_on = models.DateField('período dapesquisa', default=timezone.now) | |
created_on = models.DateTimeField('solicitado em', default=timezone.now) | |
objects = PesquisaManager() | |
class Meta: | |
verbose_name = 'Pesquisa' | |
verbose_name_plural = 'Pesquisas' | |
unique_together = (('search_key', 'question'),) | |
ordering = ('-participation_on',) | |
def __str__(self): | |
return self.question.question | |
#Pertence a uma outra app chamada person | |
class Person(models.Model): | |
name = models.CharField('Nome',max_length=100) | |
balance = models.DecimalField('Saldo', max_digits=10, decimal_places=2) | |
public_place = models.CharField('Logradouro',max_length=150) | |
number = models.CharField('Número',max_length=150) | |
city = models.CharField('Cidade',max_length=150) | |
state = models.CharField('Estado',max_length=150) | |
zipcode = models.CharField('Cep',max_length=10) | |
neighborhood = models.CharField('Bairro',max_length=50) | |
date_of_turn = models.DateField('Dt. Giro.') | |
date_return = models.DateField('Dt. Retorno.', null=True, blank=True) | |
class Meta: | |
verbose_name_plural = 'Pessoas' | |
verbose_name = 'Pessoa' | |
#------------------------------------------------------------------------------------------------------------- | |
#Minha view | |
def addQuestions(dir): | |
person = Person.objects.filter(pk=1) | |
questions = Questions.objects.all() | |
print(person) | |
lista = [] | |
for question in questions: | |
lista.append( | |
Pesquisa(search_key='092018', | |
person=person, | |
question=question, | |
response='I' | |
) | |
) | |
Pesquisa.objects.bulk_create(lista) | |
return HttpResponseRedirect('/admin/bolsa/pesquisa/') | |
#------------------------------------------------------------------------------------------------------------- | |
""" | |
Quando tento rodar a view ela retorna a seguinte mensagem: | |
Internal Server Error: /bolsa/pesquisa/criar/ | |
<QuerySet [<Person: ELIAS>]> | |
Traceback (most recent call last): | |
File "/home/elias/.virtualenvs/cobradoronline/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner | |
response = get_response(request) | |
File "/home/elias/.virtualenvs/cobradoronline/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response | |
response = self.process_exception_by_middleware(e, request) | |
File "/home/elias/.virtualenvs/cobradoronline/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response | |
response = wrapped_callback(request, *callback_args, **callback_kwargs) | |
File "/home/elias/cobradoronline/cobradoronline/bolsa/views.py", line 100, in addQuestions | |
response='I' | |
File "/home/elias/.virtualenvs/cobradoronline/lib/python3.6/site-packages/django/db/models/base.py", line 477, in __init__ | |
_setattr(self, field.name, rel_obj) | |
File "/home/elias/.virtualenvs/cobradoronline/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 197, in __set__ | |
self.field.remote_field.model._meta.object_name, | |
ValueError: Cannot assign "<QuerySet [<Person: ELIAS>]>": "Pesquisa.person" must be a "Person" instance. | |
[04/Oct/2018 21:59:16] "GET /bolsa/pesquisa/criar/ HTTP/1.1" 500 81311 | |
Ou seja, na linha 87 tem que ser uma instancia de Person. | |
O que devo fazer para corrigir este problema? | |
Leve em consideração que eu não tenho muito conhecimento heheheh | |
""" |
Substituir isso
for question in questions:
lista.append(
Pesquisa(search_key='092018',
person=person,
question=question,
response='I'
)
)
Pesquisa.objects.bulk_create(lista)
return HttpResponseRedirect('/admin/bolsa/pesquisa/')
Por
for question in questions:
Pesquisa.objects.get_or_create(
search_key='092018',
person=person,
question=question,
response='I'
)
return HttpResponseRedirect('/admin/bolsa/pesquisa/')
Obrigado!
Deu certo!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
O erro está na linha 76:
person = Person.objects.filter(pk=1)
, o filter retorna uma lista de objetos e para criar a Pesquisa você precisa de uma person só ao invés de uma lista.Melhor forma de corrigir:
person = Person.objects.get(pk=1)
- Oget
retorna apenas um e é apropriado nesse caso (pq vc está usando a chave primária, para o caso que usa outro parametro, que não a chave primaria, e ele encontre mais de um registro, ele gera uma exceção.).