On Sun, 2006-07-16 at 12:37 +0000, Paul wrote:
> I'm trying to come up with a way of writing re-useable code for certain
> common features on two-point-oh-y sites. This might become a long post,
> so apologies in advance.
> 
> Say your building the standard blog application. It's conceivable that
> you'd want your users to add comments, add tags, and rate posts.
> 
> You might have a model for comments which looks slightly like this.
> 
> class Comment(models.Model):
>       post         = models.ForeignKey(BlogPost)
>       author       = models.ForeignKey(User)
>       comment_text = models.TextField(blank=True)
> 
> something similar for tags and ratings.
> 
> Then you expand your site to add your photos, and you'd like to allow
> the same features to be used, and, in fact, the same code to be used.
> Trouble is, the models you've defined specifies that Comments work with
> BlogPosts.
> 
> Now looking at the django.contrib.comments code I see that the author
> there decided to use an integer object id rather than a ForeignKey
> 
> class Comment(models.Model):
>       parent       = models.IntegerField(('object ID'))
>       author       = models.ForeignKey(User)
>       comment_text = models.TextField(blank=True)
> 
> Ok, this means that the Comment can be used with any other item
> (assuming it has an integer primary key), but we've got BlogPosts and
> Photos on our site, and their object ids are not guaranteed to be
> unique (in fact they're likely not to be). Also we've lost the nice
> django DB API for traversing this relationship.

Have another look at the Comment model in django.contrib.comments. See
the content_type field? That provides the mapping to the right model to
use to look up the object_id. The ContentType model in Django exists to
do exactly what you are asking here: provide indirect references to
other models that are determined at run-time, rather than definition
time.

Also have a look at the GenericRelation model field that was recently
added to Django. It's not fully documented yet, nor fully supported in
the admin, but the tests provide an example of how to use it:

http://code.djangoproject.com/browser/django/trunk/tests/modeltests/generic_relations/models.py

I think you'll find that GenericRelation can help you achieve most of
what you are after. It provides exactly the sort of model-independent
lookup you seem to be seeking.

Regards,
Malcolm


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" 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-users
-~----------~----~----~----~------~----~------~--~---

Reply via email to