Django manager and queryset

◾️ We can access to DB using Manager(User.objects of User Model)

◾️ How to enter python console with Django loaded

python manage.py shell

◾️ This code returns Queryset ( making query )

$ python manage.py shell
>>> from rooms.models import Room
>>> Room.objects.all()
<QuerySet [<Room: COUPLE ROOM>, <Room: Privacy room>]>

◾️ What is a _set?

A property added on a model that's the target of a Foreign Key

◾️ Exercise

  • Room Model
from django.db import models
from django_countries.fields import CountryField
from core import models as core_models


# Create your models here.
class AbstractItem(core_models.AbstractTimeStampModel):
    """ Abstract Item """

    name = models.CharField(max_length=80)

    class Meta:
        abstract = True

    def __str__(self):
        return self.name


class Amenity(AbstractItem):
    """ Amenity Model Definition """

    class Meta:
        verbose_name_plural = "Amenities"

.....

class Room(core_models.AbstractTimeStampModel):
    """ Room Model Definition """

    name = models.CharField(max_length=140)
    description = models.TextField()
    .....
    instant_book = models.BooleanField(default=False)
    host = models.ForeignKey("users.User", on_delete=models.CASCADE)
    room_type = models.ForeignKey("RoomType", on_delete=models.SET_NULL, null=True)
    amenities = models.ManyToManyField("Amenity", blank=True)
    ......
  • Review Model
from django.db import models
from core import models as core_models


# Create your models here.
class Review(core_models.AbstractTimeStampModel):
    """ Review Model Definition """

    review = models.TextField()
    accuracy = models.IntegerField()
    .....
    user = models.ForeignKey("users.User", on_delete=models.CASCADE)
    room = models.ForeignKey("rooms.Room", on_delete=models.CASCADE)
  • query with shell
$ python manage.py shell
>>> from rooms.models import Room
>>> Room.objects.all()
<QuerySet [<Room: COUPLE ROOM>, <Room: Privacy room>]>

>>> r = Room.objects.get(name="COUPLE ROOM")
>>> r
<Room: COUPLE ROOM>

◾️ We can find 'review_set'(auto named) property.
>>> dir(r)
['DoesNotExist', 'Meta', '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_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_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks', '_perform_unique_checks', '_save_parents', '_save_table', '_set_pk_val', '_state', 'address', 'amenities', 'baths', 'bedrooms', 'beds', 'check', 'check_in', 'check_out', 'city', 'clean', 'clean_fields', 'country', 'created', 'date_error_message', 'delete', 'description', 'facilities', 'from_db', 'full_clean', 'get_country_display', 'get_deferred_fields', 'get_next_by_created', 'get_next_by_updated', 'get_previous_by_created', 'get_previous_by_updated', 'guests', 'host', 'host_id', 'house_rules', 'id', 'instant_book', 'list_set', 'name', 'objects', 'photos', 'pk', 'prepare_database_save', 'price', 'refresh_from_db', 'reservation_set'
, 'review_set', 'room_type', 'room_type_id', 'save', 'save_base', 'serializable_value', 'unique_error_message', 'updated', 'validate_unique']

>>> vars(r)
{'_state': <django.db.models.base.ModelState object at 0x110a139a0>, 'id': 1, 'created': datetime.datetime(2021, 4, 14, 13, 29, 47, 836208, tzinfo=<UTC>), 'updated': datetime.datetime(2021, 4, 16, 7, 23, 13, 904400, tzinfo=<UTC>), 'name': 'COUPLE ROOM', 'description': '14m2 couple', 'country': 'AL', 'city': 'Seoul', 'price': 1500, 'address': '신림동', 'guests': 2, 'beds': 1, 'bedrooms': 2, 'baths': 1, 'check_in': datetime.time(6, 0), 'check_out': datetime.time(22, 28, 47), 'instant_book': True, 'host_id': 1, 'room_type_id': 3}

>>> r.review_set
<django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager object at 0x11092c970>
>>> r.review_set.all()
<QuerySet [<Review: good place - COUPLE ROOM>]>

◾️ We can rename the ‘review_set’ to ‘review’ using related_name

    room = models.ForeignKey(
        "rooms.Room", related_name="reviews", on_delete=models.CASCADE
    )
◾️ We can find 'review'(renamed with related_name) property.
>>> dir(r)
['DoesNotExist', 'Meta', '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_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_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks', '_perform_unique_checks', '_save_parents', '_save_table', '_set_pk_val', '_state', 'address', 'amenities', 'baths', 'bedrooms', 'beds', 'check', 'check_in', 'check_out', 'city', 'clean', 'clean_fields', 'country', 'created', 'date_error_message', 'delete', 'description', 'facilities', 'from_db', 'full_clean', 'get_country_display', 'get_deferred_fields', 'get_next_by_created', 'get_next_by_updated', 'get_previous_by_created', 'get_previous_by_updated', 'guests', 'host', 'host_id', 'house_rules', 'id', 'instant_book', 'list_set', 'name', 'objects', 'photos', 'pk', 'prepare_database_save', 'price', 'refresh_from_db', 'reservation_set', 'reviews', 'room_type', 'room_type_id', 'save', 'save_base', 'serializable_value', 'unique_error_message', 'updated', 'validate_unique']

>>> r.reviews
<django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager object at 0x11146b370>
>>> r.reviews.all()
<QuerySet [<Review: good place - COUPLE ROOM>]>



コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です