Untitled

mail@pastecode.io avatarunknown
plain_text
a month ago
11 kB
12
Indexable
Never
In [1]: from exercises_app.models import Album, Band

In [2]: bands = Band.objects.all()

In [3]: Album.objects.create(title='sample3', year=1990, rate=5, band=bands[1])
Out[3]: <Album: Album object (1)>

In [4]: Album.objects.create(title='sample4', year=1990, rate=5, band=bands[0])
Out[4]: <Album: Album object (2)>

In [5]: Album.objects.create(title='sample5', year=1994, rate=2, band=bands[2])
Out[5]: <Album: Album object (3)>

In [6]: Album.objects.create(title='sample 6', year=1996, rate=5, band=bands[2])
Out[6]: <Album: Album object (4)>

In [7]: bands = Band.objects.all()

In [8]: print(dir(bands[2]))
['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__
', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__',
 '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__wea
kref__', '_check_column_name_clashes', '_check_constraints', '_check_default_pk', '_check_field_name_clashes', '_check_fields', '_check_i
d_field', '_check_index_together', '_check_indexes', '_check_local_fields', '_check_long_column_names', '_check_m2m_through_same_relation
ship', '_check_managers', '_check_model', '_check_model_name_db_lookup_clashes', '_check_ordering', '_check_property_name_related_field_a
ccessor_clashes', '_check_single_primary_key', '_check_swappable', '_check_unique_together', '_do_insert', '_do_update', '_get_FIELD_disp
lay', '_get_expr_references', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', '_get_unique_checks', '_
meta', '_perform_date_checks', '_perform_unique_checks', '_prepare_related_fields_for_save', '_save_parents', '_save_table', '_set_pk_val
', '_state', 'album_set', 'check', 'clean', 'clean_fields', 'date_error_message', 'delete', 'from_db', 'full_clean', 'genre', 'get_deferr
ed_fields', 'get_genre_display', 'id', 'name', 'objects', 'pk', 'prepare_database_save', 'refresh_from_db', 'save', 'save_base', 'seriali
zable_value', 'still_active', 'unique_error_message', 'validate_unique', 'year']

In [9]: print(bands[2].album_set)
exercises_app.Album.None

In [10]: print(bands[2].album_set.get())
---------------------------------------------------------------------------
MultipleObjectsReturned                   Traceback (most recent call last)
Cell In[10], line 1
----> 1 print(bands[2].album_set.get())

File D:\nauka\coderslab\sierpien\ONL_PYT_W_29_podstawy_django-main\project\venv\lib\site-packages\django\db\models\manager.py:85, in Base
Manager._get_queryset_methods.<locals>.create_method.<locals>.manager_method(self, *args, **kwargs)
     84 def manager_method(self, *args, **kwargs):
---> 85     return getattr(self.get_queryset(), name)(*args, **kwargs)

File D:\nauka\coderslab\sierpien\ONL_PYT_W_29_podstawy_django-main\project\venv\lib\site-packages\django\db\models\query.py:443, in Query
Set.get(self, *args, **kwargs)
    438 if not num:
    439     raise self.model.DoesNotExist(
    440         "%s matching query does not exist." %
    441         self.model._meta.object_name
    442     )
--> 443 raise self.model.MultipleObjectsReturned(
    444     'get() returned more than one %s -- it returned %s!' % (
    445         self.model._meta.object_name,
    446         num if not limit or num < limit else 'more than %s' % (limit - 1),
    447     )
    448 )

MultipleObjectsReturned: get() returned more than one Album -- it returned 2!

In [11]: bands[2].album_set.get()
---------------------------------------------------------------------------
MultipleObjectsReturned                   Traceback (most recent call last)
Cell In[11], line 1
----> 1 bands[2].album_set.get()

File D:\nauka\coderslab\sierpien\ONL_PYT_W_29_podstawy_django-main\project\venv\lib\site-packages\django\db\models\manager.py:85, in Base
Manager._get_queryset_methods.<locals>.create_method.<locals>.manager_method(self, *args, **kwargs)
     84 def manager_method(self, *args, **kwargs):
---> 85     return getattr(self.get_queryset(), name)(*args, **kwargs)

File D:\nauka\coderslab\sierpien\ONL_PYT_W_29_podstawy_django-main\project\venv\lib\site-packages\django\db\models\query.py:443, in Query
Set.get(self, *args, **kwargs)
    438 if not num:
    439     raise self.model.DoesNotExist(
    440         "%s matching query does not exist." %
    441         self.model._meta.object_name
    442     )
--> 443 raise self.model.MultipleObjectsReturned(
    444     'get() returned more than one %s -- it returned %s!' % (
    445         self.model._meta.object_name,
    446         num if not limit or num < limit else 'more than %s' % (limit - 1),
    447     )
    448 )

MultipleObjectsReturned: get() returned more than one Album -- it returned 2!

In [12]: bands[2].album_set.all()
Out[12]: <QuerySet [<Album: Album object (3)>, <Album: Album object (4)>]>

In [13]: [print(album.title) for album in bands[2].album_set.all()]
sample5
sample 6
Out[13]: [None, None]

In [14]: exit()

(venv) D:\nauka\coderslab\sierpien\ONL_PYT_W_29_podstawy_django-main\project>python manage.py makemigrations
Migrations for 'exercises_app':
  exercises_app\migrations\0010_song.py
    - Create model Song

(venv) D:\nauka\coderslab\sierpien\ONL_PYT_W_29_podstawy_django-main\project>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, exercises_app, football, sessions
Running migrations:
  Applying exercises_app.0010_song... OK

(venv) D:\nauka\coderslab\sierpien\ONL_PYT_W_29_podstawy_django-main\project>python manage.py shell
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.14.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from exercises_app.models import Album, Band, Song

In [2]: albums = Album.objects.all()

In [3]: Song.objects.create(title="song10", album=albums[0])
Out[3]: <Song: Song object (1)>

In [4]: Song.objects.create(title="song11", album=albums[0])
Out[4]: <Song: Song object (2)>

In [5]: Song.objects.create(title="song12", album=albums[0])
Out[5]: <Song: Song object (3)>

In [6]: Song.objects.create(title="song1", album=albums[1])
Out[6]: <Song: Song object (4)>

In [7]: Song.objects.create(title="song2", album=albums[1])
Out[7]: <Song: Song object (5)>

In [8]: Song.objects.create(title="song3", album=albums[1])
Out[8]: <Song: Song object (6)>

In [9]: bands = Band.objects.all()

In [10]: for band in bands:
    ...:     albums = band.album_set.all()
    ...:     if len(albums) > 0:
    ...:         print("albums for band", band.name)
    ...:         for album in albums:
    ...:             print("  album:", album.title)
    ...: 
albums for band Metallica
  album: sample4
albums for band Pink Floyd
  album: sample3
albums for band The Clash
  album: sample5
  album: sample 6

In [11]: albums = Album.objects.all()

In [12]: for album in albums:
    ...:     print("album :", album.title)
    ...:     songs = album.song_set.all()
    ...:     for song in songs:
    ...:         print("  song:", song.title)
    ...: 
album : sample3
  song: song10
  song: song11
  song: song12
album : sample4
  song: song1
  song: song2
  song: song3
album : sample5
album : sample 6

In [13]: exit()

(venv) D:\nauka\coderslab\sierpien\ONL_PYT_W_29_podstawy_django-main\project>python manage.py makemigrations
Migrations for 'exercises_app':
  exercises_app\migrations\0011_article_category.py
    - Add field category to article

(venv) D:\nauka\coderslab\sierpien\ONL_PYT_W_29_podstawy_django-main\project>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, exercises_app, football, sessions
Running migrations:
  Applying exercises_app.0011_article_category... OK

(venv) D:\nauka\coderslab\sierpien\ONL_PYT_W_29_podstawy_django-main\project>python manage.py shell
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.14.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from exercises_app.models import Article, Category

In [2]: albums = Album.objects.all()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[2], line 1
----> 1 albums = Album.objects.all()

NameError: name 'Album' is not defined

In [3]: from exercises_app.models import Article, Category

In [4]: articles = Article.objects.all()

In [5]: categories = Category.objects.all()

In [6]: print(categories[0].name)
ca1

In [7]: print(articles[0].title)
sample2

In [8]: articles[0].category.add(categories[0])

In [9]: articles[0].category.add(categories[1])

In [10]: dir(categories[1])
Out[10]: 
['DoesNotExist',
 'MultipleObjectsReturned',
 '__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getstate__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__setstate__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 '_check_column_name_clashes',
 '_check_constraints',
 '_check_default_pk',
 '_check_field_name_clashes',
 '_check_fields',
 '_check_id_field',
 '_check_index_together',
 '_check_indexes',
 '_check_local_fields',
 '_check_long_column_names',
 '_check_m2m_through_same_relationship',
 '_check_managers',
 '_check_model',
 '_check_model_name_db_lookup_clashes',
 '_check_ordering',
 '_check_property_name_related_field_accessor_clashes',
 '_check_single_primary_key',
 '_check_swappable',
 '_check_unique_together',
 '_do_insert',
 '_do_update',
 '_get_FIELD_display',
 '_get_expr_references',
 '_get_next_or_previous_by_FIELD',
 '_get_next_or_previous_in_order',
 '_get_pk_val',
 '_get_unique_checks',
 '_meta',
 '_perform_date_checks',
 '_perform_unique_checks',
 '_prepare_related_fields_for_save',
 '_save_parents',
 '_save_table',
 '_set_pk_val',
 '_state',
 'article_set',
 'check',
 'clean',
 'clean_fields',
 'date_error_message',
 'delete',
 'description',
 'from_db',
 'full_clean',
 'get_deferred_fields',
 'id',
 'name',
 'objects',
 'pk',
 'prepare_database_save',
 'refresh_from_db',
 'save',
 'save_base',
 'serializable_value',
 'unique_error_message',
 'validate_unique']

In [11]: categories[2].article_set.add(article[1])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[11], line 1
----> 1 categories[2].article_set.add(article[1])

NameError: name 'article' is not defined

In [12]: categories[2].article_set.add(articles[1])