PythonTip >> 博文 >> Django

about foreignKey

zihua 2014-03-04 18:03:19 点击: 657 | 收藏


#关系对象#

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 

原文链接:http://my.oschina.net/u/240562/blog/70486

作者:zihua | 分类: Django | 标签: django | 阅读: 657 | 发布于: 2014-03-04 18时 |