django中related_name是什么意思?


主要是做什么用的呢? 比如

players = models.ManyToManyField(User, related_name='cars', verbose_name=_('players'))

related_name django

御坂10033 11 years, 3 months ago

简单的讲,就是一个快捷方式设置,怎么说呢? 举个例子

from django.db import models

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

    def __unicode__(self):
        return self.name

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)

    def __unicode__(self):
        return self.headline

在上面的例子中,Entry Class, 如果 blog = models.ForeignKey(Blog)中不指定related_name,要想从Blog中访问 Entry,得通过如下方式:

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

如果使用relatedname,比如 blog = ForeignKey(Blog, relatedname='entries') 那么就变成了,

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

希望有帮助。

十六夜☆咲夜 answered 11 years, 3 months ago

Your Answer