On 26/06/2015 3:24 PM, Elim Qiu wrote:
Installed django recently, followed the django tutorial pdf to some
where arround page 20. But got problems...

It's on ubuntu 14.04, I have ipython installed and the following command
some how brings up ipython. And it will raise exception for command
Question.objects.filter(question_text__startswith='What')

I have to do double quotes instead:
Question.objects.filter(question_text__startswith="What")

But now I encountered the following error and need your help:

The last line of the traceback gives the answer ...

IntegrityError: (1048, "Column 'poll_id' cannot be null")

It's a long time since I looked at the tutorial but I seem to remember that questions each belong to a poll. So create a poll first if you haven't done so already and then make sure question is related to poll.

Try finding polls ...

<anything>.objects.all() returns a queryset even if there is only one object in it. https://docs.djangoproject.com/en/1.7/topics/db/queries/#retrieving-all-objects

Querysets are very clever because they don't hit the database until you need the actual objects. If you slice the queryset or list it, it gets evaluated and the objects it points to become available.

so ...

from polls.models import Poll
poll_qs = Poll.objects.all()

If there is at least one Poll object you can get it directly if you know enough about it to specify it in a filter() or use Poll.objects.get(id=1) (er .. that's not how you would normally do it)

<anything>.objects.get() returns one object (not a queryset) or a DoesNotExist or MultipleObjectsReturned error so you really must specify it properly.

In any case, having discovered the poll you are interested in, you need a variable to represent it. So ...

p = poll_qs[0] # this slices the first object off the queryset

... and p is the first object in the queryset.

Now retrieve the question as you did previously but this time assign it to a variable like this ...

> In [11]: q = Question.objects.get(pub_date__year=this_year)
> Out [12]: q

Now

q.poll = p
q.save()

... and that should stop the IntegrityError: (1048, "Column 'poll_id' cannot be null")

With any luck.

hth

Mike


elim@aLnx:mydjango$ python manage.py shell
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
Type "copyright", "credits" or "license" for more information.

IPython 1.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import django

In [2]: django.setup()

In [3]: from polls.models import Question, Choice

In [4]: Question.objects.all()
Out[4]: [<Question: What's up?>]

In [5]: from django.utils import timezone

In [6]: Question.objects.filter(id=1)
Out[6]: [<Question: What's up?>]

In [7]: Question.objects.filter(question_text__startswith="What")
Out[7]: [<Question: What's up?>]

In [8]: # Due to ipython instead of python shell, we need "What" instead
of 'What'

In [9]: this_year = timezone.now().year

In [10]: this_year
Out[10]: 2015

In [11]: Question.objects.get(pub_date__year=this_year)
Out[11]: <Question: What's up?>

In [12]: # Question.objects.get(id=2) will raise: Traceback (most recent
call last):

In [13]: # ...

In [14]: # DoesNotExist: Question matching query does not exist.

In [15]: Question.objects.get(id=1)
Out[15]: <Question: What's up?>

In [16]: Question.objects.get(pk=1)
Out[16]: <Question: What's up?>

In [17]: q = Question.objects.get(pk=1)

In [18]: q.was_published_recently()
Out[18]: False

In [19]: q
Out[19]: <Question: What's up?>

In [20]: # What False (In[18]) ?

In [21]: q.choice_set.all()
Out[21]: []

In [22]: q.choice_set.create(choice_text='Not much', votes=0)
---------------------------------------------------------------------------
IntegrityError                            Traceback (most recent call last)
<ipython-input-22-eb4d4c16acae> in <module>()
----> 1 q.choice_set.create(choice_text='Not much', votes=0)

/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.pyc
in create(self, **kwargs)
     748             kwargs[rel_field.name] = self.instance
     749             db = router.db_for_write(self.model,
instance=self.instance)
--> 750             return super(RelatedManager,
self.db_manager(db)).create(**kwargs)
     751         create.alters_data = True
     752

/usr/local/lib/python2.7/dist-packages/django/db/models/manager.pyc in
manager_method(self, *args, **kwargs)
     125         def create_method(name, method):
     126             def manager_method(self, *args, **kwargs):
--> 127                 return getattr(self.get_queryset(), name)(*args,
**kwargs)
     128             manager_method.__name__ = method.__name__
     129             manager_method.__doc__ = method.__doc__

/usr/local/lib/python2.7/dist-packages/django/db/models/query.pyc in
create(self, **kwargs)
     346         obj = self.model(**kwargs)
     347         self._for_write = True
--> 348         obj.save(force_insert=True, using=self.db)
     349         return obj
     350

/usr/local/lib/python2.7/dist-packages/django/db/models/base.pyc in
save(self, force_insert, force_update, using, update_fields)
     708
     709         self.save_base(using=using, force_insert=force_insert,
--> 710                        force_update=force_update,
update_fields=update_fields)
     711     save.alters_data = True
     712

/usr/local/lib/python2.7/dist-packages/django/db/models/base.pyc in
save_base(self, raw, force_insert, force_update, using, update_fields)
     736             if not raw:
     737                 self._save_parents(cls, using, update_fields)
--> 738             updated = self._save_table(raw, cls, force_insert,
force_update, using, update_fields)
     739         # Store the database on which the object was saved
     740         self._state.db = using

/usr/local/lib/python2.7/dist-packages/django/db/models/base.pyc in
_save_table(self, raw, cls, force_insert, force_update, using,
update_fields)
     820
     821             update_pk = bool(meta.has_auto_field and not pk_set)
--> 822             result = self._do_insert(cls._base_manager, using,
fields, update_pk, raw)
     823             if update_pk:
     824                 setattr(self, meta.pk.attname, result)

/usr/local/lib/python2.7/dist-packages/django/db/models/base.pyc in
_do_insert(self, manager, using, fields, update_pk, raw)
     859         """
     860         return manager._insert([self], fields=fields,
return_id=update_pk,
--> 861                                using=using, raw=raw)
     862
     863     def delete(self, using=None):

/usr/local/lib/python2.7/dist-packages/django/db/models/manager.pyc in
manager_method(self, *args, **kwargs)
     125         def create_method(name, method):
     126             def manager_method(self, *args, **kwargs):
--> 127                 return getattr(self.get_queryset(), name)(*args,
**kwargs)
     128             manager_method.__name__ = method.__name__
     129             manager_method.__doc__ = method.__doc__

/usr/local/lib/python2.7/dist-packages/django/db/models/query.pyc in
_insert(self, objs, fields, return_id, raw, using)
     918         query = sql.InsertQuery(self.model)
     919         query.insert_values(fields, objs, raw=raw)
--> 920         return
query.get_compiler(using=using).execute_sql(return_id)
     921     _insert.alters_data = True
     922     _insert.queryset_only = False

/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.pyc
in execute_sql(self, return_id)
     969         with self.connection.cursor() as cursor:
     970             for sql, params in self.as_sql():
--> 971                 cursor.execute(sql, params)
     972             if not (return_id and cursor):
     973                 return

/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.pyc in
execute(self, sql, params)
      77         start = time()
      78         try:
---> 79             return super(CursorDebugWrapper, self).execute(sql,
params)
      80         finally:
      81             stop = time()

/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.pyc in
execute(self, sql, params)
      62                 return self.cursor.execute(sql)
      63             else:
---> 64                 return self.cursor.execute(sql, params)
      65
      66     def executemany(self, sql, param_list):

/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.pyc
in execute(self, query, args)
     127             # misclassified and Django would prefer the more
logical place.
     128             if e.args[0] in self.codes_for_integrityerror:
--> 129                 six.reraise(utils.IntegrityError,
utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
     130             raise
     131

/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.pyc
in execute(self, query, args)
     122         try:
     123             # args is None means no string interpolation
--> 124             return self.cursor.execute(query, args)
     125         except Database.OperationalError as e:
     126             # Map some error codes to IntegrityError, since
they seem to be

/usr/lib/python2.7/dist-packages/MySQLdb/cursors.pyc in execute(self,
query, args)
     172             del tb
     173             self.messages.append((exc, value))
--> 174             self.errorhandler(self, exc, value)
     175         self._executed = query
     176         if not self._defer_warnings: self._warning_check()

/usr/lib/python2.7/dist-packages/MySQLdb/connections.pyc in
defaulterrorhandler(***failed resolving arguments***)
      34     del cursor
      35     del connection
---> 36     raise errorclass, errorvalue
      37
      38 re_numeric_part = re.compile(r"^(\d+)")

IntegrityError: (1048, "Column 'poll_id' cannot be null")


--
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/558D0399.2020804%40dewhirst.com.au.
For more options, visit https://groups.google.com/d/optout.

Reply via email to