Skip to content

Instantly share code, notes, and snippets.

@lalit97
Created July 3, 2021 13:26
Show Gist options
  • Save lalit97/8c3d93cb3cbaa6a95fc7befb3d501fa2 to your computer and use it in GitHub Desktop.
Save lalit97/8c3d93cb3cbaa6a95fc7befb3d501fa2 to your computer and use it in GitHub Desktop.
ajay-discussion
In [1]: from pdfs.models import Question, Choice
In [2]: Question.objects.count()
Out[2]: 0
In [3]: Choice.objects.count()
Out[3]: 0
In [4]: q = Question(
...: question_text="who is best football player?"
...: )
In [5]: q
Out[5]: <Question: Question object (None)>
In [6]: q.save()
In [7]: q
Out[7]: <Question: Question object (1)>
In [8]: choice=Choice(
...: choice_text="Ronaldo"
...: )
In [9]: choice.save()
---------------------------------------------------------------------------
IntegrityError Traceback (most recent call last)
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args)
83 else:
---> 84 return self.cursor.execute(sql, params)
85
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute(self, query, params)
382 query = self.convert_query(query)
--> 383 return Database.Cursor.execute(self, query, params)
384
IntegrityError: NOT NULL constraint failed: pdfs_choice.question_id
The above exception was the direct cause of the following exception:
IntegrityError Traceback (most recent call last)
<ipython-input-9-f990d6d45a21> in <module>
----> 1 choice.save()
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/models/base.py in save(self, force_insert, force_update, using, update_fields)
739
740 self.save_base(using=using, force_insert=force_insert,
--> 741 force_update=force_update, update_fields=update_fields)
742 save.alters_data = True
743
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/models/base.py in save_base(self, raw, force_insert, force_update, using, update_fields)
777 updated = self._save_table(
778 raw, cls, force_insert or parent_inserted,
--> 779 force_update, using, update_fields,
780 )
781 # Store the database on which the object was saved
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/models/base.py in _save_table(self, raw, cls, force_insert, force_update, using, update_fields)
868
869 update_pk = meta.auto_field and not pk_set
--> 870 result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
871 if update_pk:
872 setattr(self, meta.pk.attname, result)
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/models/base.py in _do_insert(self, manager, using, fields, update_pk, raw)
906 """
907 return manager._insert([self], fields=fields, return_id=update_pk,
--> 908 using=using, raw=raw)
909
910 def delete(self, using=None, keep_parents=False):
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/models/manager.py in manager_method(self, *args, **kwargs)
80 def create_method(name, method):
81 def manager_method(self, *args, **kwargs):
---> 82 return getattr(self.get_queryset(), name)(*args, **kwargs)
83 manager_method.__name__ = method.__name__
84 manager_method.__doc__ = method.__doc__
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/models/query.py in _insert(self, objs, fields, return_id, raw, using, ignore_conflicts)
1184 query = sql.InsertQuery(self.model, ignore_conflicts=ignore_conflicts)
1185 query.insert_values(fields, objs, raw=raw)
-> 1186 return query.get_compiler(using=using).execute_sql(return_id)
1187 _insert.alters_data = True
1188 _insert.queryset_only = False
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/models/sql/compiler.py in execute_sql(self, return_id)
1330 with self.connection.cursor() as cursor:
1331 for sql, params in self.as_sql():
-> 1332 cursor.execute(sql, params)
1333 if not return_id:
1334 return
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/backends/utils.py in execute(self, sql, params)
97 start = time()
98 try:
---> 99 return super().execute(sql, params)
100 finally:
101 stop = time()
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/backends/utils.py in execute(self, sql, params)
65
66 def execute(self, sql, params=None):
---> 67 return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
68
69 def executemany(self, sql, param_list):
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/backends/utils.py in _execute_with_wrappers(self, sql, params, many, executor)
74 for wrapper in reversed(self.db.execute_wrappers):
75 executor = functools.partial(wrapper, executor)
---> 76 return executor(sql, params, many, context)
77
78 def _execute(self, sql, params, *ignored_wrapper_args):
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args)
82 return self.cursor.execute(sql)
83 else:
---> 84 return self.cursor.execute(sql, params)
85
86 def _executemany(self, sql, param_list, *ignored_wrapper_args):
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/utils.py in __exit__(self, exc_type, exc_value, traceback)
87 if dj_exc_type not in (DataError, IntegrityError):
88 self.wrapper.errors_occurred = True
---> 89 raise dj_exc_value.with_traceback(traceback) from exc_value
90
91 def __call__(self, func):
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args)
82 return self.cursor.execute(sql)
83 else:
---> 84 return self.cursor.execute(sql, params)
85
86 def _executemany(self, sql, param_list, *ignored_wrapper_args):
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute(self, query, params)
381 return Database.Cursor.execute(self, query)
382 query = self.convert_query(query)
--> 383 return Database.Cursor.execute(self, query, params)
384
385 def executemany(self, query, param_list):
IntegrityError: NOT NULL constraint failed: pdfs_choice.question_id
In [10]: choice=Choice(
...: choice_text="Ronaldo",
...: question="who is best football player?"
...: )
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-10-b96858d80036> in <module>
1 choice=Choice(
2 choice_text="Ronaldo",
----> 3 question="who is best football player?"
4 )
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/models/base.py in __init__(self, *args, **kwargs)
481 # checked) by the RelatedObjectDescriptor.
482 if rel_obj is not _DEFERRED:
--> 483 _setattr(self, field.name, rel_obj)
484 else:
485 if val is not _DEFERRED:
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py in __set__(self, instance, value)
209 instance._meta.object_name,
210 self.field.name,
--> 211 self.field.remote_field.model._meta.object_name,
212 )
213 )
ValueError: Cannot assign "'who is best football player?'": "Choice.question" must be a "Question" instance.
In [11]: choice=Choice(
...: choice_text="Ronaldo",
...: question="who is best football player?"
...: )
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-11-b96858d80036> in <module>
1 choice=Choice(
2 choice_text="Ronaldo",
----> 3 question="who is best football player?"
4 )
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/models/base.py in __init__(self, *args, **kwargs)
481 # checked) by the RelatedObjectDescriptor.
482 if rel_obj is not _DEFERRED:
--> 483 _setattr(self, field.name, rel_obj)
484 else:
485 if val is not _DEFERRED:
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py in __set__(self, instance, value)
209 instance._meta.object_name,
210 self.field.name,
--> 211 self.field.remote_field.model._meta.object_name,
212 )
213 )
ValueError: Cannot assign "'who is best football player?'": "Choice.question" must be a "Question" instance.
In [12]: q = Question.objects.get(id=1)
In [13]: q.question_text
Out[13]: 'who is best football player?'
In [14]: choice=Choice(
...: question="who is best football player?",
...: choice_text="Ronaldo"
...: )
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-14-7aac5d458477> in <module>
1 choice=Choice(
2 question="who is best football player?",
----> 3 choice_text="Ronaldo"
4 )
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/models/base.py in __init__(self, *args, **kwargs)
481 # checked) by the RelatedObjectDescriptor.
482 if rel_obj is not _DEFERRED:
--> 483 _setattr(self, field.name, rel_obj)
484 else:
485 if val is not _DEFERRED:
~/office/pdf-merge/env/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py in __set__(self, instance, value)
209 instance._meta.object_name,
210 self.field.name,
--> 211 self.field.remote_field.model._meta.object_name,
212 )
213 )
ValueError: Cannot assign "'who is best football player?'": "Choice.question" must be a "Question" instance.
In [15]: question = Question.objects.get(id=1)
...:
...: choice=Choice(
...: question=question,
...: choice_text="Ronaldo"
...: )
In [16]: ch = choice.save()
In [17]: ch
In [18]: choice=Choice.objects.get(id=1)
In [19]: choice
Out[19]: <Choice: Choice object (1)>
In [20]: choice.__dict__
Out[20]:
{'_state': <django.db.models.base.ModelState at 0x10a3ad240>,
'id': 1,
'question_id': 1,
'choice_text': 'Ronaldo'}
In [21]: choice.choice_text
Out[21]: 'Ronaldo'
In [22]: choice.question
Out[22]: <Question: Question object (1)>
In [23]: q = choice.question
In [24]: q
Out[24]: <Question: Question object (1)>
In [25]: q.question_text
Out[25]: 'who is best football player?'
In [26]: qs = Choice.objects.filter(question_id=1)
In [27]: qs
Out[27]: <QuerySet [<Choice: Choice object (1)>]>
In [28]: qs = Choice.objects.filter(question=q)
In [29]: qs
Out[29]: <QuerySet [<Choice: Choice object (1)>]>
In [30]: que = Question.objects.get(id=1)
In [31]: que.choice_set.all()
Out[31]: <QuerySet [<Choice: Choice object (1)>]>
In [32]: choice.question
Out[32]: <Question: Question object (1)>
In [33]: q = Question(
...: question_text="questin 2"
...: )
In [34]: q.save()
In [35]: qs = Question.objects.all()
In [36]: qs
Out[36]: <QuerySet [<Question: Question object (1)>, <Question: Question object (2)>]>
In [37]: my_dic = {}
In [38]: for item in qs:
...: my_dic["question_text"] = item.question
...:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-38-c8d897191eca> in <module>
1 for item in qs:
----> 2 my_dic["question_text"] = item.question
3
AttributeError: 'Question' object has no attribute 'question'
In [39]: resp = []
In [40]: for item in qs:
...: dic = {}
...: dic["question_text"] = item.question_text
...: resp.append(dic)
...:
In [41]: resp
Out[41]:
[{'question_text': 'who is best football player?'},
{'question_text': 'questin 2'}]
In [42]: type(resp)
Out[42]: list
In [43]: import json
In [44]: json_resp = json.dumps(resp)
In [45]: json_resp
Out[45]: '[{"question_text": "who is best football player?"}, {"question_text": "questin 2"}]'
In [46]: type(json_resp)
Out[46]: str
In [47]: "JsonResponse(json_resp)"
Out[47]: 'JsonResponse(json_resp)'
In [48]: from pdfs.serializer import QuestionSerializer
In [49]: qs
Out[49]: <QuerySet [<Question: Question object (1)>, <Question: Question object (2)>]>
In [50]: resp = QuestionSerializer(qs, many=True)
In [51]: resp
Out[51]:
QuestionSerializer(<QuerySet [<Question: Question object (1)>, <Question: Question object (2)>]>, many=True):
id = IntegerField(label='ID', read_only=True)
question_text = CharField(max_length=200)
In [52]: resp.data
Out[52]: [OrderedDict([('id', 1), ('question_text', 'who is best football player?')]), OrderedDict([('id', 2), ('question_text', 'questin 2')])]
In [53]: "Response(resp.data)"
Out[53]: 'Response(resp.data)'
In [54]: serializer = QuestionSerializer(data=request.data)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-54-00e6248a0363> in <module>
----> 1 serializer = QuestionSerializer(data=request.data)
NameError: name 'request' is not defined
In [55]: request.data["question_text"]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-55-7de21890b8e7> in <module>
----> 1 request.data["question_text"]
NameError: name 'request' is not defined
In [56]: validated_data["question_text"}
File "<ipython-input-56-066b70e63eeb>", line 1
validated_data["question_text"}
^
SyntaxError: invalid syntax
In [57]: validated_data["question_text"]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-57-e4094c54feb6> in <module>
----> 1 validated_data["question_text"]
NameError: name 'validated_data' is not defined
In [58]:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment