ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Web Dev Bootcamp TIL Day-46(Django Reverse Lookup)
    TIL 2022. 6. 17. 19:27
    • The dir() method returns the list of valid attributes of the passed object.
    number = [12]
    
    # returns valid attributes of the number list 
    print(dir(number))
    
    # Output: ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
    • attributes are created when we create new attributes
    • objects that are in a many-to-many relationship contain attributes that can return a queryset of related object
    # models.py
    class User(AbstractBaseUser):
        ...
    
    class Hobby(models.Model):
        ...
    
    class UserProfile(models.Model):
        user = models.OneToOneField(User)
        hobby = models.ManyToManyField(Hobby, related_name="userprofile")
        ...
    
    # views.py
    user = User.objects.get(id=obj_id)
    hobby = Hobby.objects.get(id=obj_id)
    
    print(dir(user))
    print(dir(hobby))
    
    # result dir(user) print
    """
    [..., userprofile, ...]
    """
    
    # result dir(hobby) print
    """
    [..., userprofile_set, ...]
    """
    
    # notice that user and UserProfile have a one-to-one relationship
    # ----> user.userprofile
    # ----> Object is returned
    # on the other hand, hobby and UserProfile are in a many-to-many relationship
    # ----> hobby.userprofile_set
    # ----> Queryset is returned ... we can also use hobby.userprofile.all()
    # there can be multiple ForeignKeys for a given table, so a queryset is called when FK is used

     

     

     

    django.db.utils.IntegrityError: NOT NULL

     --> this is a very common error for beginners. It means that you have a field that is null=False (aka the default) and you're trying to create that model WITHOUT that field having any data.

Designed by Tistory.