Sunday, February 3, 2019

Re: PLEASE HELP! Django documentation, Writing Your First App, Part 4

Here is the codes about choice


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


In [28]: q.choice_set.all()

Out[28]: <QuerySet []>


In [29]: q.choice_set.create(choice_text='Not much',votes=0)

Out[29]: <Choice: Not much>


In [30]: q.choice_set.create(choice_text='The sky',votes=0)

Out[30]: <Choice: The sky>


In [31]: c = q.choice_set.create(choice_text='Just hacking again',votes=0)


In [32]: c.question

Out[32]: <Question: What's up?>


In [33]: q.choice_set.all()

Out[33]: <QuerySet [<Choice: Just hacking again>, <Choice: The sky>, <Choice: Not much>]>


In [34]: q.choice_set.count()

Out[34]: 3



choice exits, or correctly working?

Nori

On Sunday, February 3, 2019 at 10:55:48 AM UTC-5, Atsunori Kaneshige wrote:
Hi Carsten,

Sorry, are you talking about Writing Your First App, Part2? The page below?

Yeah, when I tried this, there was something wrong.

I did that again. I copied and pasted my terminal below.
seems like migration was successful when I did before.
I am not sure what 'python sqlmigrate polls 001' is doing.


MacBook-Pro-3:mysite Koitaro$ python manage.py migrate

/Applications/anaconda3/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.

  """)

Operations to perform:

  Apply all migrations: admin, auth, contenttypes, polls, sessions

Running migrations:

  No migrations to apply.

MacBook-Pro-3:mysite Koitaro$ python manage.py makemigrations polls

/Applications/anaconda3/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.

  """)

No changes detected in app 'polls'

MacBook-Pro-3:mysite Koitaro$ python manage.py sqlmigrate polls 0001

/Applications/anaconda3/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.

  """)

BEGIN;

--

-- Create model Choice

--

CREATE TABLE "polls_choice" ("id" serial NOT NULL PRIMARY KEY, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);

--

-- Create model Question

--

CREATE TABLE "polls_question" ("id" serial NOT NULL PRIMARY KEY, "question_text" varchar(200) NOT NULL, "pub_date" timestamp with time zone NOT NULL);

--

-- Add field question to choice

--

ALTER TABLE "polls_choice" ADD COLUMN "question_id" integer NOT NULL;

CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");

ALTER TABLE "polls_choice" ADD CONSTRAINT "polls_choice_question_id_c5b4b260_fk_polls_question_id" FOREIGN KEY ("question_id") REFERENCES "polls_question" ("id") DEFERRABLE INITIALLY DEFERRED;

COMMIT;

MacBook-Pro-3:mysite Koitaro$ 




After this, when I typed 'python manage.py shell',
By the way, I am not doing this in virtual environment, is it fine?
Django docs doesn't say anything about it.

Here is the result of shell

MacBook-Pro-3:mysite Koitaro$ python manage.py shell

/Applications/anaconda3/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.

  """)

Python 3.6.5 |Anaconda, Inc.| (default, Apr 26 2018, 08:42:37) 

Type 'copyright', 'credits' or 'license' for more information

IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.


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


In [2]: Question.objects.all()

Out[2]: <QuerySet [<Question: What's up?>, <Question: How's going?>, <Question: Oh, are you OK?>, <Question: Where is she?>]>


In [3]: from django.utils import timezone


In [4]: q = Question(question_text='What's up?,pub_data=timezone.now())

  File "<ipython-input-4-85ce5789a277>", line 1

    q = Question(question_text='What's up?,pub_data=timezone.now())

                                     ^

SyntaxError: invalid syntax



In [5]: q = Question(question_text="What's up?",pub_data=timezone.now())

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-5-bae574063418> in <module>()

----> 1 q = Question(question_text="What's up?",pub_data=timezone.now())


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/base.py in __init__(self, *args, **kwargs)

    483                     pass

    484             for kwarg in kwargs:

--> 485                 raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg)

    486         super().__init__()

    487         post_init.send(sender=cls, instance=self)


TypeError: 'pub_data' is an invalid keyword argument for this function


In [6]: q = Question(question_text="What's up?",pub_date=timezone.now())


In [7]: q.save()


In [8]: q.id

Out[8]: 5


In [9]: q.question_text

Out[9]: "What's up?"


In [10]: q.pub_date

Out[10]: datetime.datetime(2019, 2, 3, 15, 43, 10, 354354, tzinfo=<UTC>)


In [11]: q.question_text = "What's up?"


In [12]: q.save()


In [13]: Question.objects.all()

Out[13]: <QuerySet [<Question: What's up?>, <Question: How's going?>, <Question: Oh, are you OK?>, <Question: Where is she?>, <Question: What's up?>]>


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


In [15]: Question.objects.all()

Out[15]: <QuerySet [<Question: What's up?>, <Question: How's going?>, <Question: Oh, are you OK?>, <Question: Where is she?>, <Question: What's up?>]>


In [16]: Question.objects.filter(question_text_startswith='What')

---------------------------------------------------------------------------

FieldError                                Traceback (most recent call last)

<ipython-input-16-09474b7667e7> in <module>()

----> 1 Question.objects.filter(question_text_startswith='What')


/Applications/anaconda3/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__


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/query.py in filter(self, *args, **kwargs)

    842         set.

    843         """

--> 844         return self._filter_or_exclude(False, *args, **kwargs)

    845 

    846     def exclude(self, *args, **kwargs):


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/query.py in _filter_or_exclude(self, negate, *args, **kwargs)

    860             clone.query.add_q(~Q(*args, **kwargs))

    861         else:

--> 862             clone.query.add_q(Q(*args, **kwargs))

    863         return clone

    864 


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py in add_q(self, q_object)

   1261         # So, demotion is OK.

   1262         existing_inner = {a for a in self.alias_map if self.alias_map[a].join_type == INNER}

-> 1263         clause, _ = self._add_q(q_object, self.used_aliases)

   1264         if clause:

   1265             self.where.add(clause, AND)


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py in _add_q(self, q_object, used_aliases, branch_negated, current_negated, allow_joins, split_subq)

   1285                     child, can_reuse=used_aliases, branch_negated=branch_negated,

   1286                     current_negated=current_negated, allow_joins=allow_joins,

-> 1287                     split_subq=split_subq,

   1288                 )

   1289                 joinpromoter.add_votes(needed_inner)


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py in build_filter(self, filter_expr, branch_negated, current_negated, can_reuse, allow_joins, split_subq, reuse_with_filtered_relation)

   1162         if not arg:

   1163             raise FieldError("Cannot parse keyword query %r" % arg)

-> 1164         lookups, parts, reffed_expression = self.solve_lookup_type(arg)

   1165 

   1166         if not getattr(reffed_expression, 'filterable', True):


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py in solve_lookup_type(self, lookup)

   1026             if expression:

   1027                 return expression_lookups, (), expression

-> 1028         _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())

   1029         field_parts = lookup_splitted[0:len(lookup_splitted) - len(lookup_parts)]

   1030         if len(lookup_parts) > 1 and not field_parts:


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py in names_to_path(self, names, opts, allow_many, fail_on_missing)

   1387                     )

   1388                     raise FieldError("Cannot resolve keyword '%s' into field. "

-> 1389                                      "Choices are: %s" % (name, ", ".join(available)))

   1390                 break

   1391             # Check if we need any joins for concrete inheritance cases (the


FieldError: Cannot resolve keyword 'question_text_startswith' into field. Choices are: choice, id, pub_date, question_text


In [17]: Question.objects.filter(question_text__startswith='What')

Out[17]: <QuerySet [<Question: What's up?>, <Question: What's up?>]>


In [18]: from django.utils import timezone


In [19]: current_year = timezone.now().year


In [20]: Question.objects.get(pub_date__year=current_year)

---------------------------------------------------------------------------

MultipleObjectsReturned                   Traceback (most recent call last)

<ipython-input-20-05adfe5e79c1> in <module>()

----> 1 Question.objects.get(pub_date__year=current_year)


/Applications/anaconda3/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,<span c

--
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 django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
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/7e4ab0b3-59be-4898-bc9c-20a25b712964%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment