Malcolm Tredinnick wrote:
> On Fri, 2006-11-03 at 22:19 +0000, Rob Hudson wrote:
>> Jacob Kaplan-Moss wrote:
>>> Try this::
>>>
>>>     from innovate.innovation.models import Innovation
>>>     from django.contrib.contenttypes.models import ContentType
>>>
>>>     i = Innovation.objects.get(id=1)
>>>     ct = ContentType.objects.get_for_model(i)
>> Yeah, that's not so hard.  I updated my method to this and it worked
>> just fine.
>>
>>     def get_content_type(self):
>>         return ContentType.objects.get_for_model(self)
>>
>> Thanks.
>>
>> Besides the suggestion that this might be a good inclusion to
>> models.Model, I guess this should have gone to django-users.
> 
> If you wanted to work on this, the correct place to add the solution
> would be in django.contrib.contenttypes somewhere. Catch the
> class_prepared signal and add the relevant method (using add_to_class())
> in there. See the code at the top of django/db/models/manipulators.py
> for a similar usage (that is how we add default manipulators if none
> exist).
> 
> This sort of request has come up before, but I personally haven't worked
> on it yet, because it really needs a larger solution: if you are truly
> wanting to query content types all the time, you need to implement a
> cache for content-types or you are going to pay the penalty for frequent
> database lookups (and if you aren't doing it frequently, then the lines
> as Jacob suggested are certainly sufficiently simple to use).
> Originally, there was a suggestion to implement this caching via an
> attribute on each model (it caches its content-type). However, Jacob
> pointed out a while back that it makes more sense to cache it more
> globally (as a module-level) cache inside the ContentType app itself:
> each time we read in a model's content type, save it in memory -- in a
> module-level dictionary -- and try the cached value before trying to
> read from the database.
> 

i'm also +1 on having an easy way to "get" the content-type of a given 
object "from" the object.

in my experience, most of time i need to do this in a template.

for example, many times i have links that look like:

example.com/<model_name>/<object.id|slug>/,

and it would be really convenient to access the model's content-type 
(and this way it's "name") from the object,

so that i could write in the template:

example.com/{{ obj.ct.model }}/{{ obj.id }}/

of course, in the template it can also be solved with a custom filter,
but it seems to be a lot more elegant for me to add it to the model.

gabor

--~--~---------~--~----~------------~-------~--~----~
 You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-developers?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to