星期四, 1月 20, 2011

Generic Relation in Django

有時候,Model中的某個欄位是ForeignKey,

而偏偏又不能確定該欄位是指向什麼Model的時候該怎麼辦呢?

Generic Relation是在Django裡的好辦法!

使用方法如下:
1.給Model一個ForeignKey欄位,指向ContentType
2.再給Model一個欄位,用來儲存所要指向的Model的Primary。
在這裡注意一下,如果型態給IntegerField,那就不能指向PrimaryKey是CharField的Model囉!
3.再一個欄位,型態是GericForeignKey,然後把上面兩個欄位給它。就可以了。

文件中有個簡單的範例:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class TaggedItem(models.Model):
tag = models.SlugField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')

def __unicode__(self):
return self.tag
可以看到tag本身當然還不確定會去tag什麼model,所以就用Generic Relation是再好不過了!
執行時再決定所指向的是什麼就可以了。
>>> from django.contrib.auth.models import User
>>> guido = User.objects.get(username='Guido')
>>> t = TaggedItem(content_object=guido, tag='bdfl')
>>> t.save()
>>> t.content_object


參考自:http://docs.djangoproject.com/en/1.2/ref/contrib/contenttypes/

沒有留言: