我最近遇到了这个问题。您所做的一切都很好,但是您可以通过创建一个可以透明地逆转关系的mixin将其概括起来:
class Event(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') class meta: unique_together = ('content_type', 'object_id')class EventMixin(object): @property def get_event(self): ctype = ContentType.objects.get_for_model(self.__class__) try: event = Event.objects.get(content_type__pk = ctype.id, object_id=self.id) except: return None return eventclass Action1(EventMixin, models.Model): # Don't need to mess up the models fields (make sure the mixing it placed before models.Model) ...
和
action = Action1.object.get(id=1)event = action.get_event
您可能也想向反向关系添加缓存
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)