I did read the docs. The ubiquious 'TaggedItem' example I just
couldn't wrap my head around. I get it now though. For those who find
this looking for a solution:

Just add three fields to your model:

content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
item = generic.GenericForeignKey('content_type', 'object_id')

You can name them anything you want, as long as the names on the first
two lines match the names in the third line's constructor.

Basically the first line stores the type of object, the second line
stores the object's primarykey, and the third line is a helper thats
not even truly required, but makes it much much easier to use. Now you
can just go:

MyModel(item=WhateverModelInstanceYouWant, **other_opts)

and it should all magically work. The 'content_type' and 'object_id'
fields will be handled by the generic relation API.


On Dec 6, 4:34 am, bruno desthuilliers <bruno.desthuilli...@gmail.com>
wrote:
> On 5 déc, 20:30, mack the finger <nbvf...@gmail.com> wrote:
>
> > I can't quite wrap my brain around how to do generic relations. I have
> > a `Receipt` model which is a receipt of a purchase. One of the fields
> > is `item` which is a foreign key to a product model. I want to be able
> > to not only have products, but other things that the user can buy.
>
> > What do I need to do here to allow me to link to other types? Just
> > change the ForeignKey('Product') to generic.GenericForeignKey()? Is
> > that it?
>
> Actually it's a bit more complicated - but the good news is that it's
> documented:http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generi...
>
> Please read the above doc first, then come back if you have problems ;)

-- 
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