I want to make my Book model belongs to multiple Libraries, Collections, References and Editors, together. Is it possible to do it with generic relations? Like that:
content_type = generic.GenericManyToMany(ContentType)
from django.conf import settings
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.translation import ugettext_lazy as _
LIBRARY_NAME_MAX_LENGTH = getattr(settings, "LIBRARY_NAME_MAX_LENGTH", 160)
class Library(models.Model):
"""
"""
name = models.TextField(max_length=LIBRARY_NAME_MAX_LENGTH,
verbose_name=_(u""))
desc = models.TextField()
class Meta:
verbose_name = _(u"library")
verbose_name_plural = _(u"libraries")
class Collection(models.Model):
"""
"""
name = models.TextField()
description = models.TextField()
period = models.TextField()
class Meta:
verbose_name = _(u"collection")
verbose_name_plural = _(u"collections")
class Editor(models.Model):
"""
blabla...
"""
class Reference(models.Model):
"""
"""
title = models.TextField()
isbn = models.TextField()
editor = models.ForeignKey(Editor)
pub_date = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return _(u"%s: %s") % (self.title, self.isbn)
class Meta:
ordering = "-pub_date"
verbose_name = _(u"reference")
verbose_name_plural = _(u"references")
class Book(models.Model):开发者_如何学C
"""
"""
content_type = models.ForeignKey(ContentType)
object_pk = models.TextField()
content_object = generic.GenericForeignKey(ct_field="content_type",
fk_field="object_pk")
title = models.TextField()
cover = models.TextField()
# and some other fields
class Meta:
verbose_name = _(u"book")
verbose_name_plural = _(u"books")
I dont think there is something built into django, but a many to many relation is more or less just a connection table.
one possible solution would be to do something like this:
class Book(models.Model):
pass
class BookConnection(models.Model):
book = models.ForeignKey(Book)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
class SomeModel(models.Model):
pass
class SomeOtherModel(models.Model):
pass
to connect a book to some models:
>>> book = Book.objects.create()
>>> m1 = SomeModel.objects.create()
>>> m2 = SomeModel.objects.create()
>>> m3 = SomeOtherModel.objects.create()
>>> BookConnection.objects.create(book=book, content_object=m1)
>>> BookConnection.objects.create(book=book, content_object=m2)
>>> BookConnection.objects.create(book=book, content_object=m3)
精彩评论