about foreignKey

#關係對象#

from django.db import models

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

    def __str__(self):
        return self.name

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

    def __str__(self):
        return self.name

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateTimeField()
    authors = models.ManyToManyField(Author)

    def __str__(self):
        return self.headline

例如,b是Blog的對象, b.entry_set就能夠得到Entry的對象,就能夠操做  
1 Entry.objects.filter(blog__name__exact='Beatles Blog'),查找blog的對象的數據
2 Blog.objects.filter(entry__headline__contains='Lennon'), 反過來也能夠

3 select_related(),表示能夠把第一次查找的數據加入到緩存,第二次查找就到緩存裏面查找
   e = Entry.objects.select_related().get(id=2)
   print e.blog
   print e.blog
4. XXX_set  至關於得到XXX表的對象(必須得有一個類的實例,若是用Blog.entry_set, 發生錯誤)
   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()
5. related_name 參數
   能夠重載」XXX_set」名字.舉例,若是把」Entry」模型修改成」blog =ForeignKey(Blog, related_name=’entries’)」
6. get_FOO_display()

   GENDER_CHOICES = (
    ('M', 'Male'),
    ('F', 'Female'),
)
class Person(models.Model):
    name = models.CharField(max_length=20)
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)


p = Person(name='John', gender='M')
p.save()
p.gender
‘M’
p.get_gender_display()
 'Male'
7. get_object_or_404()

# Get the Entry with a primary key of 3
e = get_object_or_404(Entry, pk=3)

# Get the author of blog instance e with a name of 'Fred'
a = get_object_or_404(e.authors, name='Fred')

# Use a custom manager 'recent_entries' in the search for an
# entry with a primary key of 3
e = get_object_or_404(Entry.recent_entries, pk=3)

8. get_list_or_404()

get_list_or_404 行爲與 get_object_or_404() 相同,可是它用 filter() 取代了 get() 。若是列表爲空,它將引起 Http404 
相關文章
相關標籤/搜索