开发者

Extending and loading the right content type with django models

I inherited an application from another developer...and...

class LowLevelModel(models.Model):
 content = models.TextField()

 def get_absolute_url(self):
  from foo.pages.models import DynamicPage
  from django.contrib.contenttypes.models import ContentType
  my_type = ContentType.objects.get_for_model(self)    
  try:
   dynamic_page = DynamicPage.objects.get(content_type=my_type)
   return "%s%s/" % (dynamic_page.get_absolute_url(), self.slug)
  except DynamicPage.DoesNotExist:
   return "/resources/"
class HighLevelModel(LowLevelModel):
 def get_absolute_url(self):
  from foo.pages.models 开发者_JAVA百科import DynamicPage
  from django.contrib.contenttypes.models import ContentType
  my_type = ContentType.objects.get_for_model(self)    
  try:
   dynamic_page = DynamicPage.objects.get(content_type=my_type)
   return "%s%s/" % (dynamic_page.get_absolute_url(), self.slug)
  except DynamicPage.DoesNotExist:
   return "/resources/"

class ResourceFeed(Feed):
 title="Something awesome"
 link = '/resources/'
 def items(self):
  return LowLevelModel.objects.order_by('pub_date').reverse()[:5]

Naturally, this could would return the LowLevelModel absolute URL, I was wondering if anyone knew of a cheap way to call the LowLevelModel.objects without having to loop trough all the extending models in order to get the correct location on the site.


I don't know if it's what your looking for but I wrote a little weird extensions called django_subclass on github https://github.com/anthony-tresontani/django-subclass and it allows to get back the right object class when you call the base class manager (LowLevel... in this case)

You just have to register your subclassing model and it will handle that for you with external contenttype.


You might be able to use generic.GenericRelation, (see: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#reverse-generic-relations) but the relationship is a little weird with the assumption that there will only be one DynamicPage for any given model.

You can at least get rid of the duplication of get_absolute_url on HigherLevelModel. The get_absolute_url method on LowerLevelModel is generic enough to still work with any subclasses.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜