장고 - Django 1.7 -- Manager 명명법 ; _set 사용법



참고 : https://docs.djangoproject.com/en/1.7/topics/db/queries/#related-objects




Making queries


from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField()

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    n_comments = models.IntegerField()
    n_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __str__(self):              # __unicode__ on Python 2
        return self.headline



Related objects


One-to-many relationships

Forward


- ForeignKey 를 가지고 있는 model instance 는 , 모델의 attribute 르 통해 related (foreign) object 에 접근할수있다.

Example:

>>> e = Entry.objects.get(id=2)
>>> e.blog # Returns the related Blog object.



Following relationships “backward”


foreign-key model instance 는 Manaer 에 접근할수있다.  Manager 는 ForeignKey 를 가지고 있는 model 의 모든 instance 를 반환한다.

(즉, 어떤 model (Blog)에서 자신을 foreign key로 가지고 있는 모델(Entry)에 접근하기위해 Manager 이용하면 된다.)


Manager 명명법 : FOO_set   (단, FOO소문자 source model name)

Manager  : QuerySet 반환


Example:

>>> b = Blog.objects.get(id=1)
>>> b.entry_set.all() # Returns all Entry objects related to Blog.

# b.entry_set is a Manager that returns QuerySets.
>>> b.entry_set.filter(headline__contains='Lennon')
>>> b.entry_set.count()


Using a custom reverse manager




Many-to-many relationships


"reverse" model 은  소문자 original model name + '_set' 사용한다.

( reverse one-to-many relationships 과 같다 )


e = Entry.objects.get(id=3)
e.authors.all() # Returns all Author objects for this Entry.
e.authors.count()
e.authors.filter(name__contains='John')

a = Author.objects.get(id=5)
a.entry_set.all() # Returns all Entry objects for this Author.



One-to-one relationships



How are the backward relationships possible?


다른 ORM 들은 양쪽에서 relationships 을 정의 하지만, 장고는 한쪽에서만 relationship 을 정의한다.


Queries over related objects


For example, if you have a Blog object b with id=5, the following three queries would be identical:

Entry.objects.filter(blog=b) # Query using object instance
Entry.objects.filter(blog=b.id) # Query using id from instance
Entry.objects.filter(blog=5) # Query using id directly




Posted by 자유프로그램
TAG ,