开发者

Django Releationship between multiple fields

I just need a little help thinking through this, if someone could be so kind.

class object_a(models.Model):
  foo = models.blah
  bar = models.blah

class object_b(models.Model):
  foop = models.blah
  barp = model开发者_Python百科s.blah

In another model I have a class that I want to have a single relationship with both fields. For example, in the admin I want a list of both object_a and object_b objects selectable in some sort of relationship.

I know a generic relationship of some sort can do this, I just can't quite get to the end of the though. all help is appreciated.

Thanks.


Use the contenttypes framework provided by Django:

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

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

Then you can create some of your main objects:

>>> from myapp.models import object_a, object_b, Other
>>> a = object_a()
>>> a.foo = 'test'
>>> a.bar = 'value'
>>> a.save()
>>> b = object_b()
>>> b.foop = 'random'
>>> b.barp = 'values'
>>> b.save()

And then save references to them in Other objects:

>>> o1 = Other()
>>> o1.content_object = a
>>> o1.save()
>>> o2 = Other()
>>> o2.content_object = b
>>> o2.save()

Now if we ask for all the Other objects and inspect them:

>>> all = Other.objects.all()
>>> all[0].content_object
<object_a: object_a object>
>>> all[0].content_object.foo
u'test'
>>> all[1].content_object
<object_b: object_b object>
>>> all[1].content_object.foop
u'random'

By looking at the fields on the Other object, we can see how Django stores the generic relations:

>>> all[0].content_type
<ContentType: object_a>
>>> all[0].object_id
1

When you run the syncdb command to install your models, Django creates a unique ContentType object for each model. When you use generic relations, you store a foreign key to this content type entry (identifying what type of object is at the other end of the relation), and the unique ID of the model instance. The generic.GenericForeignKey field is not stored in the database, but is a wrapper which takes the content type and object ID and retrieves the actual object for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜