On Wed, Nov 17, 2010 at 11:46 PM, Marc Aymerich <glicer...@gmail.com> wrote:
> On Wed, Nov 17, 2010 at 11:36 PM, Jonas Geiregat <jo...@geiregat.org> wrote:
>> Hello,
>>
>>  Can I use django's generic relations to create a model (GenericPost) that 
>> can point to other model (APost) or model (ReviewPost) ?
>>  And then use this GenericPost model to get a list of all latest APost's and 
>> ReviewPost's ?
>>
>> I've been trying this all day long but I couldn't get around the API.
>>
>> Here's what I've done:
>>
>> from django.db import models
>> from django.contrib.contenttypes.models import ContentType
>> from django.contrib.contenttypes import generic
>>
>>
>> # Create your models here.
>>
>> class Post(models.Model):
>>    title = models.CharField(max_length=100)
>>
>>    class Meta:
>>        abstract = True
>>
>> class APost(Post):
>>    content = models.CharField(max_length=100)
>>
>> class Review(Post):
>>    rcontent = models.CharField(max_length=100)
>>
>> class GenericPost(models.Model):
>>    content_type = models.ForeignKey(ContentType)
>>    object_id = models.PositiveIntegerField()
>>    content_object = generic.GenericForeignKey('content_type', 'object_id')
>>
>>
>> Some shell code trying to build up some data:
>>
>> In [1]: from genericv.foo.models import APost, GenericPost, Review
>>
>> In [2]: a = APost(content="something")
>>
>> In [3]: a.save()
>>
>> In [4]: g = GenericPost(content_object=a)
>>
>> In [5]: g.save()
>>
>> In [6]: GenericPost.objects.all()
>> Out[6]: [<GenericPost: GenericPost object>, <GenericPost: GenericPost 
>> object>, <GenericPost: GenericPost object>, <GenericPost: GenericPost 
>> object>]
>>
>>
>>
>> Why is it that I have 4 objects already when I only have created one ?
>
> I don't know, but I try your code and I get only one object:
>
>>>> GenericPost.objects.all()
> [<GenericPost: GenericPost object>]
>
>>And how do I access that particular object by using the GenericPost model ?
>
> I'm not a master of generic relations and I donk now if this way is
> the best of, but you can use content_object manager for retrieve the

content_object is not a manager, I apologize for the confusion here.


-- 
Marc

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to