related_name在django model中的应用

今天在学习django0.95的时候遇到这样一个问题,我在一个model里面定义了两个foreignkey,都指向同一个model,结果在syncdb的时候老是报错,要我指定related_name,查到django.com上一篇文章Relating a model to another model more than once

举例说明,我定义一个model名叫Tag,

class TaggedItem(models.Model):
“”"A tag on an item.”"”
tag = models.SlugField()
content_type = models.ForeignKey(ContentType, related_name=’content’)
object_id = models.PositiveIntegerField()
content_object = models.GenericForeignKey()
owner = models.SlugField()
owner_type = models.ForeignKey(ContentType, related_name=’owner’)
owner_id = models.PositiveIntegerField()
owner_object = models.GenericForeignKey(’owner_type’, ‘owner_id’)

定义一个简单的model来测试:

class Mineral(models.Model):
name = models.CharField(maxlength=150)
hardness = models.PositiveSmallIntegerField()

m1 = Mineral(name=’m1′, hardness=1)

m1.save()

m2 = Mineral(name=’m2′, hardness=2)

m2.save()

t1 = TaggedItem(tag=’t1′, content_object=m1, owner_object=m2)

t1.save()

ct = ContentType.objects.get(name=’mineral’)

ct.owner.all()的结果是 [<TaggedItem: t1>]

ct.content.all()的结果就是[<TaggedItem: t1>]

通过related_name我们可以找到是TaggedItem的哪个具体字段指向ContentType。



你可能感兴趣的:(django)