Possible bug in prefetch_related used with Reverse generic relations

2015-02-02 Thread Todor Velichkov
Hi, guys.
About a week ago i asked the same question 

 
on stackoverflow. Since i got no response there i started to read how to 
report a bug 

 
(because I've never done it before), and this article took me here ;). I 
need more advanced opinion if this is truly a bug which should be reported 
or i just want too much from the ORM. So i will repeat myself from 
stackoverflow and explain what is all about.  

Here is some example model structure:

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, 
GenericRelation
from django.contrib.contenttypes.models import ContentType


class TaggedItem(models.Model):
 tag = models.SlugField()
 content_type = models.ForeignKey(ContentType)
 object_id = models.PositiveIntegerField()
 content_object = GenericForeignKey('content_type', 'object_id')

 def __unicode__(self):
 return self.tag

class Movie(models.Model):
 name = models.CharField(max_length=100)

 def __unicode__(self):
 return self.name


class Author(models.Model):
 name = models.CharField(max_length=100)

 def __unicode__(self):
 return self.name


class Book(models.Model):
 name = models.CharField(max_length=100)
 author = models.ForeignKey(Author)
 tags = GenericRelation(TaggedItem, related_query_name='books')

 def __unicode__(self):
 return self.name


Now, lets create some initial data:

>>> from tags.models import Book, Movie, Author, TaggedItem 
> >>> a = Author(name='E L James') 
> >>> a.save() 
> >>> b1 = Book(name='Fifty Shades of Grey', author=a) 
> >>> b1.save() 
> >>> b2 = Book(name='Fifty Shades Darker', author=a) 
> >>> b2.save() 
> >>> b3 = Book(name='Fifty Shades Freed', author=a) 
> >>> b3.save() 
> >>> t1 = TaggedItem(content_object=b1, tag='roman') 
> >>> t1.save() 
> >>> t2 = TaggedItem(content_object=b2, tag='roman') 
> >>> t2.save() 
> >>> t3 = TaggedItem(content_object=b3, tag='roman') 
> >>> t3.save() 
> >>> m1 = Movie(name='Guardians of the Galaxy') 
> >>> m1.save() 
> >>> t4 = TaggedItem(content_object=m1, tag='action movie') 
> >>> t4.save()
>

Now we can make a query like this:

> >>> TaggedItem.objects.filter(books__author__name='E L James')
> [, , ]
>

But we cant do this:

>>> TaggedItem.objects.filter(books__author__name='E L James').
> prefetch_related('books')
> Traceback (most recent call last):
> ...
> AttributeError: 'Book' object has no attribute 'object_id'
>

*Why i think this may be a bug?* 
Because of the error. Normally if *prefech_related* can't resolve a relation it 
complains like that:

AttributeError: Cannot find 'some_field' on TaggedItem object, 'some_field' 
> is an invalid parameter to prefetch_related()
>
But in the example above, Django actually tries to resolve the relation and 
fails because the ORM is searching for *object_id* inside the *Book* model 
instead of the *TaggedItem* model. 

*Why i don't use the forward relation (the `content_type` field).*
Yes, this actually will work:

>>> TaggedItem.objects.filter(books__author__name='E L James').
> prefetch_related('content_object')
> [, , ]
>
 

But this way u can't go further with the relations *against* a queryset 
containing different types of content types. 

>>> TaggedItem.objects.all().prefetch_related('content_object__author')Traceback
>>>  (most recent call last):
>   ...AttributeError: 'Movie' object has no attribute 'author_id'
>
>
 While the reversed API kind of a give me hope that it's the right way to 
go. I mean the ORM don't need to guess the author of which content types 
need  to be prefetched.

> TaggedItem.objects.all().prefetch_related('books__author')
>
We clearly show that we want the authors of all book models. nothing more, 
nothing less.

 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/557ff1af-41d2-4676-90b9-cb19b2478730%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


How to use natural keys when dumping/loading fixture data for models that use generic relations?

2014-10-02 Thread Stodge
I'm trying to create fixtures for my Django application. We have our own 
app that provides per-object permissions. It uses a GenericForeignKey to 
assign permissions to many different models. I need the ability to define 
fixtures for these custom permissions. However, I'm having trouble 
understanding how to do this properly. All of my own models have natural 
keys defined. My object permission model has a uuid field, which is 
auto-generated in the overridden save function. It's also defined as the 
natural key for this model. When I dump existing object permissions, the 
JSON includes the object_id so it's not using the natural key. Here's an 
example:

{
>
> "pk": 7, 
>
> "model": "vault.vault", 
>
> "fields": {
>
> "groups": [], 
>
> "uuid": "11d62a7b-6e38-4baf-8938-fb475d8aca52", 
>
> "system": true, 
>
> "object_id": 3, 
>>
> "content_type": [
>
> "myapp", 
>
> "mymodel"
>
> ], 
>
> "permissions": [], 
>
>     "public": false, 
>
> "users": []
>
> }
>
> }
>
>
>
I can't use this fixture as it's referencing an object ID. How do I use 
natural keys when dumping/loading fixture data for models that use generic 
relations? Thanks

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/2d978155-a274-4137-970d-dd8dabb3dcf0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Querying across Generic Relations

2013-10-28 Thread Lee Hinde
I have a table, Credit, that I want to query based on a value several hops
away. There's a CreditLineItems that has a Generic Foreign Key to one of
two tables, each of which has a Foreign Key to the table I want to search.
I've not as yet setup a reverse relation in the related tables.

My question is, given the structure below, how do I return a selection of
Credits based on a value in Registration?

class Credit(models.Model):
""" Model queried """


class CreditLineItem(models.Model):
credit = models.ForeignKey(Credit)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
 #assumed values...
# The GenericForeignKey could point to
class Enrollment(models.Model):
registration = models.ForeignKey(Registration, blank=True)

--OR--

class ProductSale(models.Model):
registration = models.ForeignKey(Registration, blank=True)

class Registration(models.Model):
registration_number =  models.IntegerField(db_index=True)

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2BePoMz2s2qowuUgs%3DnBOcde6PGTZEEg1qMYJfos-dDE3VOUHA%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Required True to Generic Relations

2012-05-15 Thread Guevara
Solution:
http://pastebin.com/011WsfzD
Regards.

On 15 maio, 23:43, Guevara <eguevara2...@gmail.com> wrote:
> Hi all!
>
> I need a required true in Generic Relations.
> Have this code:
>
> # Models
> class Client(Person):
>     addresses = GenericRelation(Address)
>
> class Address(models.Model):
>    # others fields
>     content_type = models.ForeignKey(ContentType)
>     object_id = models.PositiveIntegerField()
>     content_object = generic.GenericForeignKey('content_type',
> 'object_id')
>
> I need create a client with an address in the form.
> The DOC ignore this 
> question.https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#gener...
>
> Regards.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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.



Required True to Generic Relations

2012-05-15 Thread Guevara
Hi all!

I need a required true in Generic Relations.
Have this code:

# Models
class Client(Person):
addresses = GenericRelation(Address)

class Address(models.Model):
   # others fields
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type',
'object_id')

I need create a client with an address in the form.
The DOC ignore this question.
https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations

Regards.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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.



Excel Import Generic Relations

2011-10-23 Thread stephenstubbs
We have created an excel import application called cute_import at
https://bitbucket.org/darrenma/django-cuteimport which is able to
create and update records based on an excel spreadsheet. This works
well for one model currently. Currently it imports foreign keys based
on how they are matched up using a get or create and so will create
the foreign key if not found but only with the one field. We would
like to do something similar for generic relations and manytomany
fields before moving on to be able to import multiple tables at once.

I'm thinking of possibly matching the object on a field to a value but
not entirely sure how to do this.

object = generic.GenericForeignKey('content_type', 'object_id')

Can anyone shed some light on how this may be done?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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.



Re: Getting started with generic relations

2010-12-06 Thread mack the finger
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.



Re: Getting started with generic relations

2010-12-06 Thread bruno desthuilliers
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/#generic-relations

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.



Getting started with generic relations

2010-12-05 Thread mack the finger
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?

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



Re: Generic relations

2010-11-18 Thread Jonas Geiregat
That was it!
After running:
./manage.py sqlclear foo | ./manage.py dbshell && ./manage.py syncdb

it works!

So something in my db was inconsistent!

Thanks!

Op 18-nov-2010, om 09:57 heeft Marc Aymerich het volgende geschreven:

> On Thu, Nov 18, 2010 at 12:00 AM, Jonas Geiregat  wrote:
>> 
>> Op 17-nov-2010, om 23:46 heeft Marc Aymerich het volgende geschreven:
>> 
>> GenericPost.objects.get(pk=1).content_object.content
>> 
>> 
>> That's the strange thing. It just doesn't work:
>> 
>> Some code:
>> 
>> 
>> In [3]: GenericPost.objects.get(pk=1).content_object
>> 
>> In [4]: GenericPost.objects.get(pk=1).content_object.content
>> ---
>> AttributeErrorTraceback (most recent call last)
>> 
>> /Users/Jonas/Webdesign/genericv/ in ()
>> 
>> AttributeError: 'NoneType' object has no attribute 'content'
>> 
> 
> 
> Yep, that is very strange!. I promise that I've try exactly the same
> code that you post here and it works well with my django installation.
> I use the devel version with python 2.6.6 and mysql backend.
> 
> Try to drop your database and create a new one. Maybe you have some
> kind of inconsistency there.
> 
> -- 
> 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.
> 

Met vriendelijke groeten,

Jonas Geiregat
jo...@geiregat.org




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



Re: Generic relations

2010-11-18 Thread Marc Aymerich
On Thu, Nov 18, 2010 at 12:00 AM, Jonas Geiregat  wrote:
>
> Op 17-nov-2010, om 23:46 heeft Marc Aymerich het volgende geschreven:
>
> GenericPost.objects.get(pk=1).content_object.content
>
>
> That's the strange thing. It just doesn't work:
>
> Some code:
>
>
> In [3]: GenericPost.objects.get(pk=1).content_object
>
> In [4]: GenericPost.objects.get(pk=1).content_object.content
> ---
> AttributeError                            Traceback (most recent call last)
>
> /Users/Jonas/Webdesign/genericv/ in ()
>
> AttributeError: 'NoneType' object has no attribute 'content'
>


Yep, that is very strange!. I promise that I've try exactly the same
code that you post here and it works well with my django installation.
I use the devel version with python 2.6.6 and mysql backend.

Try to drop your database and create a new one. Maybe you have some
kind of inconsistency there.

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



Re: Generic relations

2010-11-17 Thread Jonas Geiregat

Op 17-nov-2010, om 23:46 heeft Marc Aymerich het volgende geschreven:

 GenericPost.objects.get(pk=1).content_object.content


That's the strange thing. It just doesn't work:

Some code:


In [3]: GenericPost.objects.get(pk=1).content_object

In [4]: GenericPost.objects.get(pk=1).content_object.content
---
AttributeErrorTraceback (most recent call last)

/Users/Jonas/Webdesign/genericv/ in ()

AttributeError: 'NoneType' object has no attribute 'content'





Jonas Geiregat
jo...@geiregat.org




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



Re: Generic relations

2010-11-17 Thread Marc Aymerich
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]: [, > object>, , > 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()
> []
>
>>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.



Re: Generic relations

2010-11-17 Thread Marc Aymerich
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]: [,  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()
[]

>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
object:
>>> GenericPost.objects.get(pk=1).content_object.content
u'something'



>



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



Generic relations

2010-11-17 Thread Jonas Geiregat
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]: [, , 
, ]



Why is it that I have 4 objects already when I only have created one ? And how 
do I access that particular object by using the GenericPost model ?



Regards,

Jonas Geiregat
jo...@geiregat.org




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



Re: Generic Relations: questions

2010-08-19 Thread tsmets
The more generic is yr model, the more you will find these.
and of course these join tables can grow exponentially !
What you can do is add extra fields to navigate faster or allow
partitioning of the table (it helps but not in all circumstances)

IMHO
Unless you are working for Yahoo/Google/FB/... I would not advise to
generate tables behind the scene.
Should you HAVE to do those ... use a queuing mechanism instead of
Stored Procs... it scales +/- the same (CPU-memory-... wise) BUT it is
much more robust in case of problems/failures/...
If there are no cascading delete... make sure you have clean up stored
procs to have the non-meaningfull data being purged.

I don't understand what you mean with proble 3 !

\T,


On Aug 19, 6:15 am, v0idnull <v0idn...@gmail.com> wrote:
> I asked a while back about having generic relations and someone pointed
> me tohttp://docs.djangoproject.com/en/1.2/ref/contrib/contenttypes/#generi...
>
> This wasn't what I was looking for.
>
> What I was looking for is this model I made:
>
> class Relationship(models.Model):
>
>      id = fields.UUID(auto_add=True,primary_key=True, unique=True)
>      created_by = fields.UUID(db_index=True,null=True,blank=True)
>      created_on = models.DateField(auto_now=False,auto_now_add=True)
>      modfied_on = models.DateField(auto_now=True,auto_now_add=False)
>      title = models.CharField(max_length=255)
>
>      source_id = fields.UUID(db_index=True)
>      source_app_label = models.CharField(db_index=True,max_length=255)
>      source_model = models.CharField(db_index=True,max_length=255)
>      destination_id = fields.UUID(db_index=True)
>      destination_app_label = models.CharField(db_index=True,max_length=255)
>      destination_model = models.CharField(db_index=True,max_length=255)
>
>      description = models.TextField(null=True,blank=True)
>      type =
> models.CharField(max_length=64,null=True,blank=True,db_index=True)
>      priority = models.PositiveIntegerField()
>
> Then an abstract model that all my "digital assets (ie: images,
> articles, comments, audio files, video files, etc)" extend contain these
> methods:
>
>      def getType(self):
>          if (self._type == None):
>              self._type = ContentType.objects.get_for_model(self)
>          return self._type
>
>      def relatedTo(self):
>          rels = Relationship.objects
>          return
> rels.filter(source_app_label=self.getType().app_label).filter(source_model=self.getType().model).filter(source_id=self.id)
>
>      def addRelation(self,destModel,type=None,priority=0):
>          rel = Relationship()
>          rel.destination_app_label = destModel._getType().app_label
>          rel.destination_model = destModel.getType().model
>          rel.destination_id = destModel.id
>          rel.source_app_label = self.getType().app_label
>          rel.source_model = self.getType().model
>          rel.source_id = self.id
>          rel.type = type
>          rel.priority = priority
>          rel.save()
>
> This APPEARS to do what I want it to do:
>
> 1) it describes the relationship with some meta data
> 2) it allows me to use filters to find relationships
> 3) it's not a constraint, so no cascading deletes
> 4) it's many-to-many. Any asset can be related to any other asset. It
> seems GenericForeignKey can do: "this tag is related to this bookmark",
> but it can't do "this bookmark, this article, and this photo, have these
> tags related to them"
>
> However, I see problems:
>
> 1) It's a single point of failure!!
> 2) This is a db table that can grow very quickly
> 3) I lose other functionality, like being able to quickly get an
> instance of the referenced object
>
> So I wonder if anyone has any advice. I'm new to Python and don't fully
> understand it's limitations, so I might not be thinking big enough (ie:
> I could be having behind-the-scenes functionality that automatically
> creates tables for relationships between specific model classes, but is
> that performant?).
>
> Perhaps even an existing open source project to handle these kinds of
> relationships.
>
> Thank you

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



Generic Relations: questions

2010-08-18 Thread v0idnull
I asked a while back about having generic relations and someone pointed 
me to 
http://docs.djangoproject.com/en/1.2/ref/contrib/contenttypes/#generic-relations


This wasn't what I was looking for.

What I was looking for is this model I made:

class Relationship(models.Model):

id = fields.UUID(auto_add=True,primary_key=True, unique=True)
created_by = fields.UUID(db_index=True,null=True,blank=True)
created_on = models.DateField(auto_now=False,auto_now_add=True)
modfied_on = models.DateField(auto_now=True,auto_now_add=False)
title = models.CharField(max_length=255)

source_id = fields.UUID(db_index=True)
source_app_label = models.CharField(db_index=True,max_length=255)
source_model = models.CharField(db_index=True,max_length=255)
destination_id = fields.UUID(db_index=True)
destination_app_label = models.CharField(db_index=True,max_length=255)
destination_model = models.CharField(db_index=True,max_length=255)

description = models.TextField(null=True,blank=True)
type = 
models.CharField(max_length=64,null=True,blank=True,db_index=True)

priority = models.PositiveIntegerField()

Then an abstract model that all my "digital assets (ie: images, 
articles, comments, audio files, video files, etc)" extend contain these 
methods:


def getType(self):
if (self._type == None):
self._type = ContentType.objects.get_for_model(self)
return self._type

def relatedTo(self):
rels = Relationship.objects
return 
rels.filter(source_app_label=self.getType().app_label).filter(source_model=self.getType().model).filter(source_id=self.id)


def addRelation(self,destModel,type=None,priority=0):
rel = Relationship()
rel.destination_app_label = destModel._getType().app_label
rel.destination_model = destModel.getType().model
rel.destination_id = destModel.id
rel.source_app_label = self.getType().app_label
rel.source_model = self.getType().model
rel.source_id = self.id
rel.type = type
rel.priority = priority
rel.save()

This APPEARS to do what I want it to do:

1) it describes the relationship with some meta data
2) it allows me to use filters to find relationships
3) it's not a constraint, so no cascading deletes
4) it's many-to-many. Any asset can be related to any other asset. It 
seems GenericForeignKey can do: "this tag is related to this bookmark", 
but it can't do "this bookmark, this article, and this photo, have these 
tags related to them"


However, I see problems:

1) It's a single point of failure!!
2) This is a db table that can grow very quickly
3) I lose other functionality, like being able to quickly get an 
instance of the referenced object


So I wonder if anyone has any advice. I'm new to Python and don't fully 
understand it's limitations, so I might not be thinking big enough (ie: 
I could be having behind-the-scenes functionality that automatically 
creates tables for relationships between specific model classes, but is 
that performant?).


Perhaps even an existing open source project to handle these kinds of 
relationships.


Thank you

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



generic relations with admin

2010-03-04 Thread Simon Davies
Hi

I have a shopping cart application, where by each cart can hold
several kinds of objects,  I have therefore used generic relations to
model the application along the lines of below, whereby each cart can
have many cartitems which are linked by a standard foreign key
relationship, the cartitems are in turn linked to the individual item
models by a GenericForeignKey:

class Cart(models.Model):
invoice = models.PositiveIntegerField(max_length=50, null=True,
unique=True)
datetime_added = models.DateTimeField(auto_now_add=True)
etc

class CartItem(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type',
'object_id')
cart = models.ForeignKey(Cart, related_name="items")

class AccessoryOrder(models.Model):
   cart_item = generic.GenericRelation(CartItem)

class BikePart(UsedItem):
partType = models.ForeignKey(PartType)
cart_item = generic.GenericRelation(CartItem)

class UsedBike(UsedItem):
bike = models.ForeignKey(Bike)
cart_item = generic.GenericRelation(CartItem)

This works fine, but I can't figure out a way to get what I want in
the admin app.  I have created the AccessoryOrderInline class
subclassing GenericStackedInline, but the inlines don't work in
reverse even where you have added the generic.GenericRelation
attribute to the model. The relevant parts of admin.py are:

class AccessoryOrderInline(generic.GenericStackedInline):
model = AccessoryOrder

class CartItemInline(admin.StackedInline):
model = CartItem
exclude = ('content_type', 'object_id')
extra = 0
fields = ('content.object',)
inlines = [
AccessoryOrderInline,
]

class CartAdmin(admin.ModelAdmin):
date_hierarchy = 'datetime_added'
form = CartForm
inlines = [
CartItemInline,
]

The issue is that when I click on a cart to view in admin, I the
CartItem objects but not the Accessory objects themselves,  or any
other types of item.  With the model design the way it is, I don't see
a way of getting the admin app to do what I want,  so is my model
design flawed and is there a better way of doing this using generic
relations.

Thanks

Simon

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



Re: ordering by fields in related models with Generic Relations

2010-02-17 Thread amenasse

sorry the last model was incorrectly pasted by me.



class Tag(models.Model):

# Content-object field
content_type = models.ForeignKey(ContentType,
verbose_name='content type',
related_name="content_type_set_for_%(class)s")
object_id = models.TextField('object ID')
content_object = generic.GenericForeignKey(ct_field="content_type",  
fk_field="object_id")



class Foo(models.Model):

tags = generic.GenericRelation(Tag,
content_type_field='content_type',
object_id_field='object_id'
)

name = models.CharField(max_length=150)
creation_date = models.DateTimeField(auto_now_add=True)

class Meta:
ordering = ['name',]

def __unicode__(self):
return self.name



class Bar(models.Model):

tags = generic.GenericRelation(Tag,
content_type_field='content_type',
object_id_field='object_id'
)

name = models.CharField(max_length=150)
creation_date = models.DateTimeField(auto_now_add=True)


class Meta:
ordering = ['name',]

def __unicode__(self):
return self.name


heres a dbpaste which is much easier to read:

http://dpaste.com/160832/

On Feb 18, 2010 12:48pm, sysantmin  wrote:

Hello,







I have a Tag model which has a Generic Foreign Key .





I want to order a query on the Tag model by fields in related models



(related via the Generic Foreign Key), for Example:




>>> [ o.content_object for o in  
Tag.objects.order_by('content_type__id','foo__name','bar__name') ]







Gives me:





[,



,



,



,



,



]







What i'm after is :







[,



,



,



,



,



]









Any suggestions appreciated. Right now im looking at sorting the



result of the Query Set in python which isn't ideal.





I am using Django 1.1







Heres my model:







from django.db import models





from django.contrib.contenttypes.models import ContentType



from django.contrib.contenttypes import generic





class Tag(models.Model):





# Content-object field



content_type = models.ForeignKey(ContentType,



verbose_name='content type',



related_name="content_type_set_for_%(class)s")



object_id = models.TextField('object ID')



content_object = generic.GenericForeignKey(ct_field="content_type",



fk_field="object_id")







class Foo(models.Model):





tags = generic.GenericRelation(Tag,





content_type_field='content_type',



object_id_field='object_id'



)





name = models.CharField(max_length=150)



creation_date = models.DateTimeField(auto_now_add=True)





class Meta:



ordering = ['name',]





def __unicode__(self):



return self.name





class Bar(models.Model):





tags = generic.GenericRelation(Tag,





content_type_field='content_type',



object_id_field='object_id'



)





name = models.CharField(max_length=150)



creation_date = models.DateTimeField(auto_now_add=True)







class Meta:



ordering = ['name',]





def __unicode__(self):



return self.name









Thanks



Ant










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



ordering by fields in related models with Generic Relations

2010-02-17 Thread sysantmin
Hello,


I have a Tag model which has a Generic Foreign Key .

I want to order a query on the Tag model  by fields in related models
(related via the Generic Foreign Key), for Example:

>>>  [ o.content_object for o in 
>>> Tag.objects.order_by('content_type__id','foo__name','bar__name') ]


Gives me:

[,
 ,
 ,
 ,
 ,
 ]


What i'm after is :


[,
 ,
 ,
 ,
 ,
 ]



Any suggestions appreciated. Right now im looking at sorting the
result of the Query Set in python which isn't ideal.

I am using Django 1.1


Heres my model:


from django.db import models

from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Tag(models.Model):

  # Content-object field
  content_type   = models.ForeignKey(ContentType,
  verbose_name='content type',
  related_name="content_type_set_for_%(class)s")
  object_id  = models.TextField('object ID')
  content_object = generic.GenericForeignKey(ct_field="content_type",
fk_field="object_id")


class Foo(models.Model):

tags =  generic.GenericRelation(Tag,
 
content_type_field='content_type',
object_id_field='object_id'
   )

name = models.CharField(max_length=150)
creation_date = models.DateTimeField(auto_now_add=True)

class Meta:
  ordering = ['name',]

def __unicode__(self):
  return self.name

class Bar(models.Model):

tags =  generic.GenericRelation(Tag,
 
content_type_field='content_type',
object_id_field='object_id'
   )

name = models.CharField(max_length=150)
creation_date = models.DateTimeField(auto_now_add=True)


class Meta:
  ordering = ['name',]

 def __unicode__(self):
  return self.name



Thanks
Ant




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



Re: Generic Relations and Django Admin?

2010-01-20 Thread Victor Hooi
heya,

Hmm, I'm using generic.GenericTabularInline for the Address Inline, is
that the same?

class AddressAdmin(VersionAdmin):
exclude = ('content_type', 'object_id',)
...
class AddressInline(generic.GenericTabularInline):
model = Address
...
class HospitalAdmin(admin.ModelAdmin):
inlines = [
AddressInline,
]
...

Is there an error in the above?

Also, I'm still confused on whether I should have that exclude in
there? And the bug that Raffaele Salmaso pointed out (http://
code.djangoproject.com/ticket/12577), is that what's causing this?
(The traceback in the ticket is quite different to the traceback I'm
getting).

Cheers,
Victor

Cheers,
Victor

On Jan 19, 9:55 pm, Daniel Roseman <dan...@roseman.org.uk> wrote:
> On Jan 19, 10:35 am, Victor Hooi <victorh...@gmail.com> wrote:
>
> > heya,
>
> > Thanks for the reply =).
>
> > I tried that, and the fields aren't there, but when I try to save the
> > object, I get a:
>
> >     IntegrityError at /admin/people/address/add/
> >     people_address.content_type_id may not be NULL
>
> > so obvoiusly Django doesn't like it if those fields aren't filled.
>
> > How do people normally do this sort of thing, with a polymorphic
> > object that's referenced by multiple other objects?
>
> Edit the address inline with the parent object (hospital, etc) by
> using the generic.GenericInlineAdmin class - works exactly the same as
> a normal inline admin class, but using generic relations.
> --
> DR.
-- 
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.




Re: Generic Relations and Django Admin?

2010-01-20 Thread Victor Hooi
heya,

The thing is, it's a one-to-many for UserProfile/Hospital/Institution
to Addresses - that is, each entity can (and probably will) have
multiple addresses. That's why the FK field is on Address.

Also, I thought that was the way it was traditionally modelled in
database design? (I admit I'm often confused by this part, so anybody
that can shed light on the rationale for one way or another, please
chime in).

Cheers,
Victor

On Jan 20, 12:20 am, LostCruz  wrote:
> Hi Victor,
>
> You are trying to do this the wrong way around. It shouldn't be the
> Adress class on which you want to define a relationship, but on the
> other classes. An address is an address whether it's the address of a
> User or the address of an Institution.
>
> class Address(models.Model):
>     # the field up until and including 'country'
>
> class Hostpital(models.Model):
>     name = models.CharField(max_length=20)
>     address = ForeignKey(Address)
>
> class YourUserClass(models.Model):
>     # all kinds of fields
>     address = ForeignKey(Address)
>
> Using Django's ORM system you then can get related Users and Hospitals
>
> Hope this helps.
>
> On 19 jan, 06:25, Victor Hooi  wrote:
>
>
>
> > heya,
>
> > I'm trying to use an "Address" model as a generic relation against
> > multiple other models (e.g. in a "User Profile", for each User, as
> > well as for "Building", "Institution", and various other ones).
>
> > So I've added the content_type, object_id and content_object fields to
> > Address.
>
> > class Address(models.Model):
> >     """
> >     Basic object for holding address information - for either people
> > or institutions.
> >     """
> >     street_address = models.CharField(max_length=50)
> >     suburb = models.CharField(max_length=20)
> >     state = models.CharField(max_length=3,
> > choices=AUSTRALIAN_STATES_CHOICES)
> >     # PositiveIntegerField doesn't allow max_length? Have to use form
> > validation for this.
> >     postcode = models.CharField(max_length=4)
> >     # This should probably be a list of choices.
> >     country = models.CharField(max_length=20)
> >     address_category = models.OneToOneField(AddressCategory)
>
> >     # We make Address a generic relation model
> >     content_type = models.ForeignKey(ContentType)
> >     object_id = models.PositiveIntegerField()
> >     content_object = generic.GenericForeignKey('content_type',
> > 'object_id')
>
> >     class Meta:
> >         verbose_name_plural = 'Addresses'
>
> >     def __unicode__(self):
> >         return self.street_address + ', ' + self.suburb
>
> >  And my other objects have GenericRelations to Address. E.g.:
>
> > class Hospital(models.Model):
> >     name = models.CharField(max_length=20)
> >     address = generic.GenericRelation(Address)
>
> >     def __unicode__(self):
> >         return self.name
>
> > However, when I try and use the Django admin to add an Address item,
> > the form has fields for content_type and object_id. I had thought
> > these fields wouldn't appear? Also, the model won't validate/save if I
> > don't fill in these fields. I don't think I'm quite using this right -
> > is there a better way of doing what I'm trying to achieve here?
>
> > Also, I'm using the Address object as in Inline for the other models,
> > so I have an Address Inline as well (Nb: I'm using django-reversion
> > with this site, hence the "VersionAdmin")
>
> > class AddressAdmin(VersionAdmin):
> >     pass
> > class AddressInline(generic.GenericTabularInline):
> >     model = Address
> > ...
> > class HospitalAdmin(admin.ModelAdmin):
> >     inlines = [
> >         AddressInline,
> >     ]
> > ...
> > admin.site.register(Address, AddressAdmin)
>
> > Thanks,
> > Victor
-- 
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.




Re: Generic Relations and Django Admin?

2010-01-19 Thread LostCruz
Hi Victor,

You are trying to do this the wrong way around. It shouldn't be the
Adress class on which you want to define a relationship, but on the
other classes. An address is an address whether it's the address of a
User or the address of an Institution.

class Address(models.Model):
# the field up until and including 'country'

class Hostpital(models.Model):
name = models.CharField(max_length=20)
address = ForeignKey(Address)

class YourUserClass(models.Model):
# all kinds of fields
address = ForeignKey(Address)

Using Django's ORM system you then can get related Users and Hospitals

Hope this helps.

On 19 jan, 06:25, Victor Hooi  wrote:
> heya,
>
> I'm trying to use an "Address" model as a generic relation against
> multiple other models (e.g. in a "User Profile", for each User, as
> well as for "Building", "Institution", and various other ones).
>
> So I've added the content_type, object_id and content_object fields to
> Address.
>
> class Address(models.Model):
>     """
>     Basic object for holding address information - for either people
> or institutions.
>     """
>     street_address = models.CharField(max_length=50)
>     suburb = models.CharField(max_length=20)
>     state = models.CharField(max_length=3,
> choices=AUSTRALIAN_STATES_CHOICES)
>     # PositiveIntegerField doesn't allow max_length? Have to use form
> validation for this.
>     postcode = models.CharField(max_length=4)
>     # This should probably be a list of choices.
>     country = models.CharField(max_length=20)
>     address_category = models.OneToOneField(AddressCategory)
>
>     # We make Address a generic relation model
>     content_type = models.ForeignKey(ContentType)
>     object_id = models.PositiveIntegerField()
>     content_object = generic.GenericForeignKey('content_type',
> 'object_id')
>
>     class Meta:
>         verbose_name_plural = 'Addresses'
>
>     def __unicode__(self):
>         return self.street_address + ', ' + self.suburb
>
>  And my other objects have GenericRelations to Address. E.g.:
>
> class Hospital(models.Model):
>     name = models.CharField(max_length=20)
>     address = generic.GenericRelation(Address)
>
>     def __unicode__(self):
>         return self.name
>
> However, when I try and use the Django admin to add an Address item,
> the form has fields for content_type and object_id. I had thought
> these fields wouldn't appear? Also, the model won't validate/save if I
> don't fill in these fields. I don't think I'm quite using this right -
> is there a better way of doing what I'm trying to achieve here?
>
> Also, I'm using the Address object as in Inline for the other models,
> so I have an Address Inline as well (Nb: I'm using django-reversion
> with this site, hence the "VersionAdmin")
>
> class AddressAdmin(VersionAdmin):
>     pass
> class AddressInline(generic.GenericTabularInline):
>     model = Address
> ...
> class HospitalAdmin(admin.ModelAdmin):
>     inlines = [
>         AddressInline,
>     ]
> ...
> admin.site.register(Address, AddressAdmin)
>
> Thanks,
> Victor
-- 
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.




Re: Generic Relations and Django Admin?

2010-01-19 Thread Daniel Roseman
On Jan 19, 10:35 am, Victor Hooi <victorh...@gmail.com> wrote:
> heya,
>
> Thanks for the reply =).
>
> I tried that, and the fields aren't there, but when I try to save the
> object, I get a:
>
>     IntegrityError at /admin/people/address/add/
>     people_address.content_type_id may not be NULL
>
> so obvoiusly Django doesn't like it if those fields aren't filled.
>
> How do people normally do this sort of thing, with a polymorphic
> object that's referenced by multiple other objects?
>

Edit the address inline with the parent object (hospital, etc) by
using the generic.GenericInlineAdmin class - works exactly the same as
a normal inline admin class, but using generic relations.
--
DR.
-- 
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.




Re: Generic Relations and Django Admin?

2010-01-19 Thread Raffaele Salmaso
Victor Hooi wrote:
> I tried that, and the fields aren't there, but when I try to save the
> object, I get a:
> 
> IntegrityError at /admin/people/address/add/
> people_address.content_type_id may not be NULL
> 
> so obvoiusly Django doesn't like it if those fields aren't filled.
it's a bug http://code.djangoproject.com/ticket/12577

> How do people normally do this sort of thing, with a polymorphic
> object that's referenced by multiple other objects?
use this hack until it's fixed

if 'django.contrib.contenttypes' in settings.INSTALLED_APPS:
# patch django.contrib.contenttypes.generic.BaseGenericInlineFormSet
# to provide the instance.pk
# see http://code.djangoproject.com/ticket/12577
from django.contrib.contenttypes import generic

def save_new(self, form, commit=True):
# Avoid a circular import.
from django.contrib.contenttypes.models import ContentType
kwargs = {
self.ct_field.get_attname():
ContentType.objects.get_for_model(self.instance).pk,
self.ct_fk_field.get_attname(): self.instance.pk,
}
new_obj = self.model(**kwargs)
return generic.save_instance(form, new_obj, commit=commit)
setattr(generic.BaseGenericInlineFormSet, 'save_new', save_new)

-- 
()_() | That said, I didn't actually _test_ my patch.  | +
(o.o) | That's what users are for! | +---+
'm m' |   (Linus Torvalds) |  O  |
(___) |  raffaele dot salmaso at gmail dot com |
-- 
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.




Re: Generic Relations and Django Admin?

2010-01-19 Thread Victor Hooi
heya,

Thanks for the reply =).

I tried that, and the fields aren't there, but when I try to save the
object, I get a:

IntegrityError at /admin/people/address/add/
people_address.content_type_id may not be NULL

so obvoiusly Django doesn't like it if those fields aren't filled.

How do people normally do this sort of thing, with a polymorphic
object that's referenced by multiple other objects?

Cheers,
Victor

On Jan 19, 5:59 pm, Raffaele Salmaso 
wrote:
> Victor Hooi wrote:
> > class AddressAdmin(VersionAdmin):
> >     pass
> > class AddressInline(generic.GenericTabularInline):
> >     model = Address
> > ...
>
>       fields = (the fields you want to display)
> or
>       exclude = ('content_type', 'object_id',)
>
> > class HospitalAdmin(admin.ModelAdmin):
> >     inlines = [
> >         AddressInline,
> >     ]
> > ...
> > admin.site.register(Address, AddressAdmin)
>
> --
> ()_() | That said, I didn't actually _test_ my patch.      | +
> (o.o) | That's what users are for!                         | +---+
> 'm m' |                                   (Linus Torvalds) |  O  |
> (___) |              raffaele dot salmaso at gmail dot com |
-- 
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.




Re: Generic Relations and Django Admin?

2010-01-19 Thread Victor Hooi
heya,

The thing is, the foreign key field is on the Address object, linking
to another object that *has* an address.

AFAIK, that's how it's meant to be in database design.

That's why I need to put something there - e.g.

class Address(models.Model):
...
user = models.ForeignKey(UserProfile)

but that doesn't work for hospitals, or say institutions, or anything
else that needs an address. So I can't just pick one. Or is my design
off?

Cheers,
Victor

On Jan 19, 6:03 pm, greatlemer  wrote:
> On Jan 19, 5:25 am, Victor Hooi  wrote:
>
>
>
> > heya,
>
> > I'm trying to use an "Address" model as a generic relation against
> > multiple other models (e.g. in a "User Profile", for each User, as
> > well as for "Building", "Institution", and various other ones).
>
> > So I've added the content_type, object_id and content_object fields to
> > Address.
>
> > class Address(models.Model):
> >     """
> >     Basic object for holding address information - for either people
> > or institutions.
> >     """
> >     street_address = models.CharField(max_length=50)
> >     suburb = models.CharField(max_length=20)
> >     state = models.CharField(max_length=3,
> > choices=AUSTRALIAN_STATES_CHOICES)
> >     # PositiveIntegerField doesn't allow max_length? Have to use form
> > validation for this.
> >     postcode = models.CharField(max_length=4)
> >     # This should probably be a list of choices.
> >     country = models.CharField(max_length=20)
> >     address_category = models.OneToOneField(AddressCategory)
>
> >     # We make Address a generic relation model
> >     content_type = models.ForeignKey(ContentType)
> >     object_id = models.PositiveIntegerField()
> >     content_object = generic.GenericForeignKey('content_type',
> > 'object_id')
>
> >     class Meta:
> >         verbose_name_plural = 'Addresses'
>
> >     def __unicode__(self):
> >         return self.street_address + ', ' + self.suburb
>
> >  And my other objects have GenericRelations to Address. E.g.:
>
> > class Hospital(models.Model):
> >     name = models.CharField(max_length=20)
> >     address = generic.GenericRelation(Address)
>
> >     def __unicode__(self):
> >         return self.name
>
> > However, when I try and use the Django admin to add an Address item,
> > the form has fields for content_type and object_id. I had thought
> > these fields wouldn't appear? Also, the model won't validate/save if I
> > don't fill in these fields. I don't think I'm quite using this right -
> > is there a better way of doing what I'm trying to achieve here?
>
> > Also, I'm using the Address object as in Inline for the other models,
> > so I have an Address Inline as well (Nb: I'm using django-reversion
> > with this site, hence the "VersionAdmin")
>
> > class AddressAdmin(VersionAdmin):
> >     pass
> > class AddressInline(generic.GenericTabularInline):
> >     model = Address
> > ...
> > class HospitalAdmin(admin.ModelAdmin):
> >     inlines = [
> >         AddressInline,
> >     ]
> > ...
> > admin.site.register(Address, AddressAdmin)
>
> > Thanks,
> > Victor
>
> Hi,
>
> I think here what you're looking for is to use:
> address = models.ForeignKey(Address)
> rather than a GenericRelation.  GenericRelations are for cases when
> you don't know what the target model should be (hence the extra
> content_type field).
>
> --
> G
-- 
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.




Re: Generic Relations and Django Admin?

2010-01-18 Thread greatlemer
On Jan 19, 5:25 am, Victor Hooi  wrote:
> heya,
>
> I'm trying to use an "Address" model as a generic relation against
> multiple other models (e.g. in a "User Profile", for each User, as
> well as for "Building", "Institution", and various other ones).
>
> So I've added the content_type, object_id and content_object fields to
> Address.
>
> class Address(models.Model):
>     """
>     Basic object for holding address information - for either people
> or institutions.
>     """
>     street_address = models.CharField(max_length=50)
>     suburb = models.CharField(max_length=20)
>     state = models.CharField(max_length=3,
> choices=AUSTRALIAN_STATES_CHOICES)
>     # PositiveIntegerField doesn't allow max_length? Have to use form
> validation for this.
>     postcode = models.CharField(max_length=4)
>     # This should probably be a list of choices.
>     country = models.CharField(max_length=20)
>     address_category = models.OneToOneField(AddressCategory)
>
>     # We make Address a generic relation model
>     content_type = models.ForeignKey(ContentType)
>     object_id = models.PositiveIntegerField()
>     content_object = generic.GenericForeignKey('content_type',
> 'object_id')
>
>     class Meta:
>         verbose_name_plural = 'Addresses'
>
>     def __unicode__(self):
>         return self.street_address + ', ' + self.suburb
>
>  And my other objects have GenericRelations to Address. E.g.:
>
> class Hospital(models.Model):
>     name = models.CharField(max_length=20)
>     address = generic.GenericRelation(Address)
>
>     def __unicode__(self):
>         return self.name
>
> However, when I try and use the Django admin to add an Address item,
> the form has fields for content_type and object_id. I had thought
> these fields wouldn't appear? Also, the model won't validate/save if I
> don't fill in these fields. I don't think I'm quite using this right -
> is there a better way of doing what I'm trying to achieve here?
>
> Also, I'm using the Address object as in Inline for the other models,
> so I have an Address Inline as well (Nb: I'm using django-reversion
> with this site, hence the "VersionAdmin")
>
> class AddressAdmin(VersionAdmin):
>     pass
> class AddressInline(generic.GenericTabularInline):
>     model = Address
> ...
> class HospitalAdmin(admin.ModelAdmin):
>     inlines = [
>         AddressInline,
>     ]
> ...
> admin.site.register(Address, AddressAdmin)
>
> Thanks,
> Victor

Hi,

I think here what you're looking for is to use:
address = models.ForeignKey(Address)
rather than a GenericRelation.  GenericRelations are for cases when
you don't know what the target model should be (hence the extra
content_type field).

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




Re: Generic Relations and Django Admin?

2010-01-18 Thread Raffaele Salmaso
Victor Hooi wrote:
> class AddressAdmin(VersionAdmin):
> pass
> class AddressInline(generic.GenericTabularInline):
> model = Address
> ...
  fields = (the fields you want to display)
or
  exclude = ('content_type', 'object_id',)

> class HospitalAdmin(admin.ModelAdmin):
> inlines = [
> AddressInline,
> ]
> ...
> admin.site.register(Address, AddressAdmin)

-- 
()_() | That said, I didn't actually _test_ my patch.  | +
(o.o) | That's what users are for! | +---+
'm m' |   (Linus Torvalds) |  O  |
(___) |  raffaele dot salmaso at gmail dot com |
-- 
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.




Generic Relations and Django Admin?

2010-01-18 Thread Victor Hooi
heya,

I'm trying to use an "Address" model as a generic relation against
multiple other models (e.g. in a "User Profile", for each User, as
well as for "Building", "Institution", and various other ones).

So I've added the content_type, object_id and content_object fields to
Address.

class Address(models.Model):
"""
Basic object for holding address information - for either people
or institutions.
"""
street_address = models.CharField(max_length=50)
suburb = models.CharField(max_length=20)
state = models.CharField(max_length=3,
choices=AUSTRALIAN_STATES_CHOICES)
# PositiveIntegerField doesn't allow max_length? Have to use form
validation for this.
postcode = models.CharField(max_length=4)
# This should probably be a list of choices.
country = models.CharField(max_length=20)
address_category = models.OneToOneField(AddressCategory)

# We make Address a generic relation model
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type',
'object_id')

class Meta:
verbose_name_plural = 'Addresses'

def __unicode__(self):
return self.street_address + ', ' + self.suburb

 And my other objects have GenericRelations to Address. E.g.:

class Hospital(models.Model):
name = models.CharField(max_length=20)
address = generic.GenericRelation(Address)

def __unicode__(self):
return self.name

However, when I try and use the Django admin to add an Address item,
the form has fields for content_type and object_id. I had thought
these fields wouldn't appear? Also, the model won't validate/save if I
don't fill in these fields. I don't think I'm quite using this right -
is there a better way of doing what I'm trying to achieve here?

Also, I'm using the Address object as in Inline for the other models,
so I have an Address Inline as well (Nb: I'm using django-reversion
with this site, hence the "VersionAdmin")

class AddressAdmin(VersionAdmin):
pass
class AddressInline(generic.GenericTabularInline):
model = Address
...
class HospitalAdmin(admin.ModelAdmin):
inlines = [
AddressInline,
]
...
admin.site.register(Address, AddressAdmin)

Thanks,
Victor
-- 
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.




Re: null = True and blank = True in contenttypes generic relations: why not ?

2010-01-18 Thread Karen Tracey
On Mon, Jan 18, 2010 at 3:58 AM, Alessandro Pasotti <apaso...@gmail.com>wrote:

> Hello,
>
> I would like to have a table with optional pointers to other tables
> items, generic relations would do it fine, the only problem seems to
> be the fact that generic forreign keys don't accept null values.
>
> Any hint or idea about why NOT NULL is enforced in this kind of relations ?
>

What is enforced is what you specify for the underlying database fields.
Modifying the doc example to allow these to be empty:

class TaggedItem(models.Model):
tag = models.SlugField()
content_type = models.ForeignKey(ContentType, null=True, blank=True)
object_id = models.PositiveIntegerField(null=True, blank=True)
content_object = generic.GenericForeignKey('content_type', 'object_id')

allows creation of objects that have no specified contect_object:

>>> from ttt.models import TaggedItem
>>> ti = TaggedItem.objects.create(tag='Empty')
>>> ti

>>> ti.content_object
>>>

Karen
-- 

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.



null = True and blank = True in contenttypes generic relations: why not ?

2010-01-18 Thread Alessandro Pasotti
Hello,

I would like to have a table with optional pointers to other tables
items, generic relations would do it fine, the only problem seems to
be the fact that generic forreign keys don't accept null values.

Any hint or idea about why NOT NULL is enforced in this kind of relations ?


-- 
Alessandro Pasotti
w3:   www.itopen.it
-- 
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.




Re: Questions about ContentType generic relations

2009-11-16 Thread Daniel Roseman
On Nov 16, 8:12 am, Continuation  wrote:
> > As the docs show, when you've defined a GenericRelation, querying is
> > exactly the same as with a reverse foreign key. So:
> > Bookmark.objects.get(tags__tag='django')
>
> A somewhat related question:
>
> What if instead of having a ForeignKey to ContentType, TaggedItem has
> a direct ForeignKey to Bookmark.
>
> In that case is there something similar to GenericRelation that I can
> define for Bookmark so that I can still use Bookmark.objects.get
> (tags__tag='django') (or something similar) to find all bookmarks with
> the tag "django"?
>
> The doc said "You cannot access a reverse ForeignKey Manager from the
> class; it must be accessed from an instance", but  in this case I
> really need to start with the class Bookmark instead of an instance.
> So what can I do?
>
> Thanks.

It works exactly the same, as the document I linked to shows. The
syntax you give should work with a standard ForeignKey - did you try
it?
--
DR.

--

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




Re: Questions about ContentType generic relations

2009-11-16 Thread Continuation

> As the docs show, when you've defined a GenericRelation, querying is
> exactly the same as with a reverse foreign key. So:
> Bookmark.objects.get(tags__tag='django')
>

A somewhat related question:

What if instead of having a ForeignKey to ContentType, TaggedItem has
a direct ForeignKey to Bookmark.

In that case is there something similar to GenericRelation that I can
define for Bookmark so that I can still use Bookmark.objects.get
(tags__tag='django') (or something similar) to find all bookmarks with
the tag "django"?

The doc said "You cannot access a reverse ForeignKey Manager from the
class; it must be accessed from an instance", but  in this case I
really need to start with the class Bookmark instead of an instance.
So what can I do?

Thanks.

--

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




Re: Questions about ContentType generic relations

2009-11-15 Thread Dennis Kaarsemaker
On zo, 2009-11-15 at 00:13 -0800, Continuation wrote:

> I checked out the doc (http://docs.djangoproject.com/en/dev/topics/db/
> queries/) and can't find reference to it. Can you explain its usage a
> bit more or point me to the relevant section of the doc?

http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships

-- 
Dennis K.

The universe tends towards maximum irony. Don't push it.

--

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




Re: Questions about ContentType generic relations

2009-11-15 Thread Daniel Roseman
On Nov 15, 8:13 am, Continuation  wrote:
> > As the docs show, when you've defined a GenericRelation, querying is
> > exactly the same as with a reverse foreign key. So:
> > Bookmark.objects.get(tags__tag='django')
>
> I don't quite understand your use of tags__tag='django' in retrieving
> the objects. I've never seen this usage before.
>
> I checked out the doc (http://docs.djangoproject.com/en/dev/topics/db/
> queries/) and can't find reference to it. Can you explain its usage a
> bit more or point me to the relevant section of the doc?
>
> Thanks.

This is the way of crossing joins in Django lookups - for filters,
sorting, etc - and comes up pretty much everywhere. See here:
http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships
--
DR.

--

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




Re: Questions about ContentType generic relations

2009-11-15 Thread Continuation

>
> As the docs show, when you've defined a GenericRelation, querying is
> exactly the same as with a reverse foreign key. So:
> Bookmark.objects.get(tags__tag='django')
>


I don't quite understand your use of tags__tag='django' in retrieving
the objects. I've never seen this usage before.

I checked out the doc (http://docs.djangoproject.com/en/dev/topics/db/
queries/) and can't find reference to it. Can you explain its usage a
bit more or point me to the relevant section of the doc?

Thanks.

--

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




Re: Questions about ContentType generic relations

2009-11-14 Thread esatterwh...@wi.rr.com
You might want to do a search on django-tagging. this has been done
and done well.

On Nov 13, 6:04 pm, Continuation <selforgani...@gmail.com> wrote:
> How do I do queries when ContentType is involved?
>
> Using the example in the doc 
> (http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1
> )
>
> class TaggedItem(models.Model):
>     tag = models.SlugField()
>     content_type = models.ForeignKey(ContentType)
>     object_id = models.PositiveIntegerField()
>     content_object = generic.GenericForeignKey('content_type',
> 'object_id')
>
> class Bookmark(models.Model):
>     url = models.URLField()
>     tags = generic.GenericRelation(TaggedItem)
>
> So say I attached a bunch of tags to a bunch of bookmarks.
>
> How do I get a list of all bookmarks that have the tag "django"?
>
> Also what kind of SQL statements are generated behind the scene to
> enable this querying over generic relations?
>
> Say I have many different classes (e.g. Bookmark, ForumPost,
> WikiEntry, QnA, Message, Photo, etc) that I want to attach tags to.
>
> If I want to find all the bookmarks, forum posts, wiki entries, Q,
> messages, photos, etc that have the tag "django", can I do it in 1
> statement or would I have to do it separately for each class?
>
> Thanks

--

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




Re: Questions about ContentType generic relations

2009-11-14 Thread Daniel Roseman
On Nov 14, 12:04 am, Continuation <selforgani...@gmail.com> wrote:
> How do I do queries when ContentType is involved?
>
> Using the example in the doc 
> (http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1
> )
>
> class TaggedItem(models.Model):
>     tag = models.SlugField()
>     content_type = models.ForeignKey(ContentType)
>     object_id = models.PositiveIntegerField()
>     content_object = generic.GenericForeignKey('content_type',
> 'object_id')
>
> class Bookmark(models.Model):
>     url = models.URLField()
>     tags = generic.GenericRelation(TaggedItem)
>
> So say I attached a bunch of tags to a bunch of bookmarks.
>
> How do I get a list of all bookmarks that have the tag "django"?
>
> Also what kind of SQL statements are generated behind the scene to
> enable this querying over generic relations?
>
> Say I have many different classes (e.g. Bookmark, ForumPost,
> WikiEntry, QnA, Message, Photo, etc) that I want to attach tags to.
>
> If I want to find all the bookmarks, forum posts, wiki entries, Q,
> messages, photos, etc that have the tag "django", can I do it in 1
> statement or would I have to do it separately for each class?
>
> Thanks

As the docs show, when you've defined a GenericRelation, querying is
exactly the same as with a reverse foreign key. So:
Bookmark.objects.get(tags__tag='django')

You can't get all the different objects tagged as 'django' in a single
go  - you would have to do:
[t.content_object for t in TaggedItems.objects.filter(slug='django')]

To find out what queries are being generated for this, set DEBUG=True
and look at django.db.connection.queries.
--
DR.

--

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




Questions about ContentType generic relations

2009-11-13 Thread Continuation
How do I do queries when ContentType is involved?

Using the example in the doc ( 
http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1
)

class TaggedItem(models.Model):
tag = models.SlugField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type',
'object_id')

class Bookmark(models.Model):
url = models.URLField()
tags = generic.GenericRelation(TaggedItem)

So say I attached a bunch of tags to a bunch of bookmarks.

How do I get a list of all bookmarks that have the tag "django"?

Also what kind of SQL statements are generated behind the scene to
enable this querying over generic relations?

Say I have many different classes (e.g. Bookmark, ForumPost,
WikiEntry, QnA, Message, Photo, etc) that I want to attach tags to.

If I want to find all the bookmarks, forum posts, wiki entries, Q,
messages, photos, etc that have the tag "django", can I do it in 1
statement or would I have to do it separately for each class?

Thanks

--

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




Using generic relations as an inline - not working

2009-11-11 Thread neridaj

I'm trying to add some model fields to another model for admin editing
and can't seem to get it to work i.e., model doesn't show up in admin,
inline or otherwise.

project/app/admin.py

from project.app.models import SearchKeyword
from django.contrib.flatpages.models import FlatPage
from django.contrib import admin
from django.contrib.contenttypes import generic

class KeywordInline(generic.GenericStackedInline):
model = SearchKeyword

class PageAdmin(admin.ModelAdmin):
inlines = [
KeywordInline,
]

admin.site.register(PageAdmin)



project/app/models.py

from django.db import models
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage

class SearchKeyword(models.Model):
keyword = models.CharField(max_length=50)
page = models.ForeignKey(FlatPage)

def __unicode__(self):
return self.keyword
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



Re: Newbie question on ContentTypes and Generic Relations

2009-06-14 Thread Rana

Dear Daniel,

Thanks so much for your help. I tried what you suggested and it works
just as I need it to. Thank you again.

Kind Regards,
Rana


On Jun 13, 3:01 am, Daniel Roseman <dan...@roseman.org.uk> wrote:
> On Jun 12, 8:54 pm, Rana <rd4...@gmail.com> wrote:
>
>
>
> > Hi,
>
> > I am trying to modify a blog and article model that will both display
> > data from a related products model. I read that the way I should do
> > this is through the ContentTypes framework and generic foreign
> > relations. I would be grateful for some guidance on how to do this.
> > I've read the documentation on 
> > thehttp://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
> > website, but I am struggling with how to relate it to what I need to
> > do.
>
> > I have something like this presently:
>
> > articles/models.py
> > ---
> > class Article(models.Model):
> >         author = models.ForeignKey(User, related_name='article_author')
> >         headline = models.CharField(max_length=256)
> >         publish_content = models.TextField(blank=True)
> >         ...
> >         related_product = models.ManyToManyField('RelatedProduct', 
> > null=True,
> > blank=True)
>
> > class RelatedProduct(models.Model):
> >         product_name = models.CharField(max_length=256)
> >         product_link = models.TextField(max_length=512)
>
> > blogs/models.py
> > 
> > class Blog(models.Model):
> >         name = models.CharField(max_length=128)
> >         long_description = models.TextField()
> >         short_description = models.TextField()
>
> > I would like to modify this so that I can have the related products
> > from articles also available in my Blog class and the related products
> > table should be the same between Article class and Blog class, i.e. I
> > do not want to have two instances of the RelatedProduct class.
>
> > Thank you for any help you can offer.
>
> > Rana
>
> You don't need generic relations here, just add a related_product
> ManyToMany field do the Blog model in exactly the same way as you did
> for the Article model.
> --
> DR.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



Re: Newbie question on ContentTypes and Generic Relations

2009-06-13 Thread Daniel Roseman

On Jun 12, 8:54 pm, Rana <rd4...@gmail.com> wrote:
> Hi,
>
> I am trying to modify a blog and article model that will both display
> data from a related products model. I read that the way I should do
> this is through the ContentTypes framework and generic foreign
> relations. I would be grateful for some guidance on how to do this.
> I've read the documentation on 
> thehttp://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
> website, but I am struggling with how to relate it to what I need to
> do.
>
> I have something like this presently:
>
> articles/models.py
> ---
> class Article(models.Model):
>         author = models.ForeignKey(User, related_name='article_author')
>         headline = models.CharField(max_length=256)
>         publish_content = models.TextField(blank=True)
>         ...
>         related_product = models.ManyToManyField('RelatedProduct', null=True,
> blank=True)
>
> class RelatedProduct(models.Model):
>         product_name = models.CharField(max_length=256)
>         product_link = models.TextField(max_length=512)
>
> blogs/models.py
> 
> class Blog(models.Model):
>         name = models.CharField(max_length=128)
>         long_description = models.TextField()
>         short_description = models.TextField()
>
> I would like to modify this so that I can have the related products
> from articles also available in my Blog class and the related products
> table should be the same between Article class and Blog class, i.e. I
> do not want to have two instances of the RelatedProduct class.
>
> Thank you for any help you can offer.
>
> Rana

You don't need generic relations here, just add a related_product
ManyToMany field do the Blog model in exactly the same way as you did
for the Article model.
--
DR.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



Newbie question on ContentTypes and Generic Relations

2009-06-12 Thread Rana

Hi,

I am trying to modify a blog and article model that will both display
data from a related products model. I read that the way I should do
this is through the ContentTypes framework and generic foreign
relations. I would be grateful for some guidance on how to do this.
I've read the documentation on the 
http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
website, but I am struggling with how to relate it to what I need to
do.

I have something like this presently:

articles/models.py
---
class Article(models.Model):
author = models.ForeignKey(User, related_name='article_author')
headline = models.CharField(max_length=256)
publish_content = models.TextField(blank=True)
...
related_product = models.ManyToManyField('RelatedProduct', null=True,
blank=True)

class RelatedProduct(models.Model):
product_name = models.CharField(max_length=256)
product_link = models.TextField(max_length=512)


blogs/models.py

class Blog(models.Model):
name = models.CharField(max_length=128)
long_description = models.TextField()
short_description = models.TextField()

I would like to modify this so that I can have the related products
from articles also available in my Blog class and the related products
table should be the same between Article class and Blog class, i.e. I
do not want to have two instances of the RelatedProduct class.

Thank you for any help you can offer.

Rana

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



Re: Generic relations and unit tests.

2009-04-16 Thread Stavros

Is there some way I can empty the contenttypes table before the
fixtures are loaded and have django load them normally? That would
take care of this problem, as it would mean that the proper
contenttypes would get loaded from the fixture. Unfortunately, I have
not been able to find a way to run code between creating the tables
and loading the fixture, in which I assume I need to do something like
ContentType.objects.delete().

Thanks for your help,
Poromenos

On Apr 11, 3:47 am, Russell Keith-Magee 
wrote:
> On Sat, Apr 11, 2009 at 5:53 AM,Poromenos wrote:
>
> > Hello,
> > I created a model that has a ForeignKey to ContentType, but now I
> > can't use my test fixtures, since the IDs they point to are random
> > every time the test database is created. I can't dump the contenttypes
> > data because then I get many duplicate inserts, since Django rebuilds
> > them every time it sets up the test DB. Is there any way for me to use
> > both ContentType and unit tests?
>
> The IDs won't be completely random, but they certainly will be fragile
> and subject to change.
>
> You have discovered ticket #7052; unfortunately, there isn't any easy
> fix at the moment.
>
> 1) Don't use fixtures - create your test objects in the setUp() method
> of your test using normal Python code.
>
> 2) Use the fixture to define the basic data in your objects, and then
> use the setUp() method to modify the contenttypes at runtime, based on
> the current values in the database. This means you don't serialize the
> contenttype objects themselves in your fixture, and you use and
> foreignkey reference to a contenttype as a temporary placeholder for
> the real value that will be inserted at runtime.
>
> Obviously, neither of these are ideal solutions. This bug is something
> I want to look at for Django v1.2.
>
> Yours
> Russ Magee %-)
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



Re: Generic relations swamp

2009-04-14 Thread zayatzz

Ok your idea worked just fine, but i keep coming up with new
questions :)

The result of it was that when i opened poll i got poll with name


So i wrote something (i dont know how its called - model instance?
model manager?) to retrieve the actual value of translation and my
poll model looks like this now :
class Poll(models.Model):
name = generic.GenericRelation(Trans)
pub_date = models.DateTimeField('date published')
active = models.BooleanField()
def __unicode__(self):
return unicode(self.name)
def tname(self):
q = Trans.objects.filter(poll = self)
q = q.get(keel = 1)
t = q.name
return t

Can this query also be shorter? and better? cause the first line seems
not to filter out anything at all.

Another one - this might solve the problem for displaying poll names
in list view, but when im creating questions for this poll, then in
the selectbox where i choose to which poll question belongs to i still
have poll name as
.
How could that be changed? Can it be changed withing admin.py of my
app?

Alan

On Apr 14, 3:45 pm, matehat  wrote:
> Sorry about the last post (was a little tired from a sleepless night
> of solving problems in physics ...). I think you can solve the issue
> by putting "return unicode(self.name)" instead of "return self.name"
> in all of the __unicode__ method of your models. The things is that
> you must make sure to return unicode object in that method.
>
> Another thing that pops in my mind from inspecting your code is that
> line in TranslationInline,
>
> >class TranslationInline(generic.GenericTabularInline):
> >        model = Trans
> >        extra = len(lang.objects.all())
>
> where it would be more efficient to do :
>
> extra = lang.objects.count()
>
> But that's just optimization stuff...
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



Re: Generic relations swamp

2009-04-14 Thread zayatzz



On Apr 14, 3:45 pm, matehat  wrote:
> Sorry about the last post (was a little tired from a sleepless night
> of solving problems in physics ...). I think you can solve the issue
> by putting "return unicode(self.name)" instead of "return self.name"
> in all of the __unicode__ method of your models. The things is that
> you must make sure to return unicode object in that method.
>
> Another thing that pops in my mind from inspecting your code is that
> line in TranslationInline,
>
> >class TranslationInline(generic.GenericTabularInline):
> >        model = Trans
> >        extra = len(lang.objects.all())
>
> where it would be more efficient to do :
>
> extra = lang.objects.count()
>
> But that's just optimization stuff...

Thanks for the info and tip :). I'll test it as soon as i get home.

Perhaps you can provide little more help about the django admin. That
extra there is meant to provide exactly right amount of fields for
each object, that i create, but if you use one saving option of django
admin you get more fields, which are completely unnecessary. Is there
a simple way to limit the amount of those fields and nothing more?

Alan.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



Re: Generic relations swamp

2009-04-14 Thread matehat

Sorry about the last post (was a little tired from a sleepless night
of solving problems in physics ...). I think you can solve the issue
by putting "return unicode(self.name)" instead of "return self.name"
in all of the __unicode__ method of your models. The things is that
you must make sure to return unicode object in that method.

Another thing that pops in my mind from inspecting your code is that
line in TranslationInline,

>class TranslationInline(generic.GenericTabularInline):
>model = Trans
>extra = len(lang.objects.all())

where it would be more efficient to do :

extra = lang.objects.count()

But that's just optimization stuff...


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



Re: Generic relations swamp

2009-04-12 Thread zayatzz

Admin for language:
from kyss.front.models import lang
from django.contrib import admin
class FrontAdmin(admin.ModelAdmin):
fieldsets = [
('General info', {'fields': ['name', 'short', 'locale', 
'encoding',
'url', 'fdef', 'bdef']}),
('SEO stuff', {'fields': ['title', 'metadesc', 'metakeyw',
'websitename', 'websiteslogan']}),
]

admin.site.register(lang, FrontAdmin)

Admin for poll and translations:
from kyss.poll.models import Poll
from kyss.poll.models import Question
from kyss.poll.models import Choice
from kyss.poll.models import Trans
from kyss.front.models import lang
from django.contrib import admin
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class QuestionInline(admin.TabularInline):
model = Question
extra = 2

class ChoiceInline(admin.TabularInline):
model = Choice
extra = 4

class TranslationInline(generic.GenericTabularInline):
model = Trans
extra = len(lang.objects.all())

class TransAdmin(admin.ModelAdmin):
list_display = ['id', 'name']

class QuestionAdmin(admin.ModelAdmin):
inlines = [ TranslationInline ]

class ChoiceAdmin(admin.ModelAdmin):
inlines = [ TranslationInline ]

class PollAdmin(admin.ModelAdmin):
fieldsets = [
('Date information', {'fields': ['pub_date'], 'classes':
['collapse']}),
('Is this poll active', {'fields': ['active'] }),
]
inlines = [ TranslationInline ]

admin.site.register(Poll, PollAdmin)
admin.site.register(Question, QuestionAdmin)
admin.site.register(Choice, ChoiceAdmin)
admin.site.register(Trans, TransAdmin)

Models have not been changed.

Alan.
On Apr 12, 4:27 pm, matehat  wrote:
> Hi,
>
> can you show us the code for each of your admin classes? This probably
> has something to do with some method overrides, but I can't say much
> about the cause of your problem from the error message you gave...
>
> Cheers
>
> Mathieu
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



Re: Generic relations swamp

2009-04-12 Thread matehat

Hi,

can you show us the code for each of your admin classes? This probably
has something to do with some method overrides, but I can't say much
about the cause of your problem from the error message you gave...

Cheers

Mathieu
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



Re: Generic relations swamp

2009-04-11 Thread zayatzz

I realise im kind of spamming here, but does nobody really has
encountered similar problem?

Alan.

On Apr 11, 12:07 am, zayatzz <alan.kesselm...@gmail.com> wrote:
> Ok, I did some search on web and i took closer look at the
> errormessage. :
>
> Request information
> GET
>
> No GET data
> POST
> Variable        Value
> poll-trans-content_type-object_id-0-keel
> u'1'
> poll-trans-content_type-object_id-0-id
> u''
> poll-trans-content_type-object_id-1-keel
> u'2'
> poll-trans-content_type-object_id-TOTAL_FORMS
> u'2'
> _save
> u'Save'
> poll-trans-content_type-object_id-1-name
> u'Pollname in russian'
> pub_date_1
> u'23:45:15'
> pub_date_0
> u'2009-04-10'
> poll-trans-content_type-object_id-1-id
> u''
> active
> u'on'
> poll-trans-content_type-object_id-0-name
> u'Pollname in estonian'
> poll-trans-content_type-object_id-INITIAL_FORMS
> u'0'
>
> If i understand this correctly then the content object id is not
> beeing saved - it does not save the id of the poll with the
> translations. Is this correct? And how can i fix this?
>
> I found many threads about incomplete generic relations support in
> admin - they were from '07 or so, so the things could be different.
> And i found this :http://djangoplugables.com/projects/django-genericadmin/
>
> Could this be of any use?
>
> Would anything else help?
>
> Thanks!
> Alan
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



Re: Generic relations and unit tests.

2009-04-11 Thread Stavros

I agree with you on this, but it is often impractical due to the
volume of the data required. I have this data already in my database,
I shouldn't have to spend a few days moving it to the tests file...
Fixtures are a quick way to import your data to the test DB without
having to recreate everything... I'd really like a better solution to
this, as I can use either tests or contenttype at the moment and I'd
like to use both...

Thanks,
Stavros

On Apr 11, 3:54 am, Malcolm Tredinnick 
wrote:
> On Sat, 2009-04-11 at 08:47 +0800, Russell Keith-Magee wrote:
> > On Sat, Apr 11, 2009 at 5:53 AM, Poromenos  wrote:
>
> > > Hello,
> > > I created a model that has a ForeignKey to ContentType, but now I
> > > can't use my test fixtures, since the IDs they point to are random
> > > every time the test database is created. I can't dump the contenttypes
> > > data because then I get many duplicate inserts, since Django rebuilds
> > > them every time it sets up the test DB. Is there any way for me to use
> > > both ContentType and unit tests?
>
> > The IDs won't be completely random, but they certainly will be fragile
> > and subject to change.
>
> > You have discovered ticket #7052; unfortunately, there isn't any easy
> > fix at the moment.
>
> > 1) Don't use fixtures - create your test objects in the setUp() method
> > of your test using normal Python code.
>
> > 2) Use the fixture to define the basic data in your objects, and then
> > use the setUp() method to modify the contenttypes at runtime, based on
> > the current values in the database. This means you don't serialize the
> > contenttype objects themselves in your fixture, and you use and
> > foreignkey reference to a contenttype as a temporary placeholder for
> > the real value that will be inserted at runtime.
>
> > Obviously, neither of these are ideal solutions. This bug is something
> > I want to look at for Django v1.2.
>
> Well, I'd argue (1) is the ideal solution. Creating objects
> programmatically is robust, self-documenting and encourages testers to
> think about the minimum requirements needed for a self-contained
> unittest. It's also fairly easy. Tends to be my normal practice.
>
> So opinions clearly differ there. Which doesn't invalidate Russell's
> opinion, but I wouldn't want people to think it's all horrible when
> there's already a perfectly standard and supported way of doing this
> (the setUp() method exists to set things up for unittests).
>
> 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 django-users@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
-~--~~~~--~~--~--~---



Re: Generic relations and unit tests.

2009-04-10 Thread Malcolm Tredinnick

On Sat, 2009-04-11 at 08:47 +0800, Russell Keith-Magee wrote:
> On Sat, Apr 11, 2009 at 5:53 AM, Poromenos  wrote:
> >
> > Hello,
> > I created a model that has a ForeignKey to ContentType, but now I
> > can't use my test fixtures, since the IDs they point to are random
> > every time the test database is created. I can't dump the contenttypes
> > data because then I get many duplicate inserts, since Django rebuilds
> > them every time it sets up the test DB. Is there any way for me to use
> > both ContentType and unit tests?
> 
> The IDs won't be completely random, but they certainly will be fragile
> and subject to change.
> 
> You have discovered ticket #7052; unfortunately, there isn't any easy
> fix at the moment.
> 
> 1) Don't use fixtures - create your test objects in the setUp() method
> of your test using normal Python code.
> 
> 2) Use the fixture to define the basic data in your objects, and then
> use the setUp() method to modify the contenttypes at runtime, based on
> the current values in the database. This means you don't serialize the
> contenttype objects themselves in your fixture, and you use and
> foreignkey reference to a contenttype as a temporary placeholder for
> the real value that will be inserted at runtime.
> 
> Obviously, neither of these are ideal solutions. This bug is something
> I want to look at for Django v1.2.

Well, I'd argue (1) is the ideal solution. Creating objects
programmatically is robust, self-documenting and encourages testers to
think about the minimum requirements needed for a self-contained
unittest. It's also fairly easy. Tends to be my normal practice.

So opinions clearly differ there. Which doesn't invalidate Russell's
opinion, but I wouldn't want people to think it's all horrible when
there's already a perfectly standard and supported way of doing this
(the setUp() method exists to set things up for unittests).

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 django-users@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
-~--~~~~--~~--~--~---



Re: Generic relations and unit tests.

2009-04-10 Thread Russell Keith-Magee

On Sat, Apr 11, 2009 at 5:53 AM, Poromenos  wrote:
>
> Hello,
> I created a model that has a ForeignKey to ContentType, but now I
> can't use my test fixtures, since the IDs they point to are random
> every time the test database is created. I can't dump the contenttypes
> data because then I get many duplicate inserts, since Django rebuilds
> them every time it sets up the test DB. Is there any way for me to use
> both ContentType and unit tests?

The IDs won't be completely random, but they certainly will be fragile
and subject to change.

You have discovered ticket #7052; unfortunately, there isn't any easy
fix at the moment.

1) Don't use fixtures - create your test objects in the setUp() method
of your test using normal Python code.

2) Use the fixture to define the basic data in your objects, and then
use the setUp() method to modify the contenttypes at runtime, based on
the current values in the database. This means you don't serialize the
contenttype objects themselves in your fixture, and you use and
foreignkey reference to a contenttype as a temporary placeholder for
the real value that will be inserted at runtime.

Obviously, neither of these are ideal solutions. This bug is something
I want to look at for Django v1.2.

Yours
Russ Magee %-)

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



Generic relations and unit tests.

2009-04-10 Thread Poromenos

Hello,
I created a model that has a ForeignKey to ContentType, but now I
can't use my test fixtures, since the IDs they point to are random
every time the test database is created. I can't dump the contenttypes
data because then I get many duplicate inserts, since Django rebuilds
them every time it sets up the test DB. Is there any way for me to use
both ContentType and unit tests?
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



Re: Generic relations swamp

2009-04-10 Thread zayatzz

Ok, I did some search on web and i took closer look at the
errormessage. :

Request information
GET

No GET data
POST
VariableValue
poll-trans-content_type-object_id-0-keel
u'1'
poll-trans-content_type-object_id-0-id
u''
poll-trans-content_type-object_id-1-keel
u'2'
poll-trans-content_type-object_id-TOTAL_FORMS
u'2'
_save
u'Save'
poll-trans-content_type-object_id-1-name
u'Pollname in russian'
pub_date_1
u'23:45:15'
pub_date_0
u'2009-04-10'
poll-trans-content_type-object_id-1-id
u''
active
u'on'
poll-trans-content_type-object_id-0-name
u'Pollname in estonian'
poll-trans-content_type-object_id-INITIAL_FORMS
u'0'

If i understand this correctly then the content object id is not
beeing saved - it does not save the id of the poll with the
translations. Is this correct? And how can i fix this?

I found many threads about incomplete generic relations support in
admin - they were from '07 or so, so the things could be different.
And i found this :
http://djangoplugables.com/projects/django-genericadmin/

Could this be of any use?

Would anything else help?

Thanks!
Alan
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



Re: Generic relations swamp

2009-04-10 Thread zayatzz

does anyone know how to solve this problem?

Alan

On 9 apr, 21:54, zayatzz <alan.kesselm...@gmail.com> wrote:
> Thanks.
>
> That worked for enabling translations for poll names - i had to insert
> 'from django.contrib.contenttypes import generic', right?
> It worked, but it raised few more questions. When creating poll i get
> lines for name translations now and in front of each of them there is
> language drop down menu, where i can choose to which language this
> translation belongs to. How can i replace that with just language
> name. Do i have to create some kind of loop for that view (/poll/poll/
> add), so i just get correct amount of name translations and nothing
> else?
>
> in any case it worked, but when i tried to save that poll i got this
> error :
>
> Request URL:    http://127.0.0.1:8000/admin/poll/poll/add/
> Exception Type:         TypeError
> Exception Value:        coercing to Unicode: need string or buffer,
> GenericRelatedObjectManager found
>
> Runnin search on that error i found 
> :http://mail.python.org/pipermail/python-list/2006-July/566947.html
>
> Does that mean, that connection between translation and poll name
> failed or something else at all?
>
> Alan.
>
> On Apr 9, 6:36 pm, matehat <mathieu.damo...@gmail.com> wrote:
>
> > First of all, the ModelAdmin needs to know about how to handle the
> > generic relations and whether you even need them to appear. You need
> > to subclass "generic.GenericTabularInline" (in the same way you
> > subclassed "admin.ModelAdmin") and specify fields you want to be able
> > to edit on that Trans object (probably only the "name" field if I
> > understood right) and the actual model (here Trans). Then, you'd need
> > to add the 'inlines' attribute to your PollAdmin and add the
> > GenericTabularInline subclass. So your code should look something
> > like :
>
> >http://dpaste.com/30763/
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



Re: Generic relations swamp

2009-04-09 Thread matehat

First of all, the ModelAdmin needs to know about how to handle the
generic relations and whether you even need them to appear. You need
to subclass "generic.GenericTabularInline" (in the same way you
subclassed "admin.ModelAdmin") and specify fields you want to be able
to edit on that Trans object (probably only the "name" field if I
understood right) and the actual model (here Trans). Then, you'd need
to add the 'inlines' attribute to your PollAdmin and add the
GenericTabularInline subclass. So your code should look something
like :

http://dpaste.com/30763/
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



Generic relations swamp

2009-04-09 Thread zayatzz

Seriously. Im reading and reading, but cant understand much or i just
dont find good examples.

What i have is model structure like this :

I have language model, which holds website generic data like language
parameter, encoding, website titles, metainfo and so on

Then i have bit more complex poll system with models like:
poll, question, choices and translation.

Translation model is like this :
class Trans(models.Model):
keel = models.ForeignKey(lang) #for knowing to which language this
translation belongs to
content_type = models.ForeignKey(ContentType) # this and 2 lines
below it are for generic relations as good as i understand them
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
name= models.CharField(max_length=500) # for the translation itself
def __unicode__(self):
return self.name

Other models are like this :
class Poll(models.Model):
name = generic.GenericRelation(Trans)
pub_date = models.DateTimeField('date published')
active = models.BooleanField()
def __unicode__(self):
return self.name
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()

class Question(models.Model):
TYPE_CHOICES = (
('1', 'single answer'),
('2', 'multiple choices'),
('3', 'Textfield'),
)
poll = models.ForeignKey(Poll)
nr = models.IntegerField()
name = generic.GenericRelation(Trans)
qtype = models.CharField(max_length=1, choices = TYPE_CHOICES)
def __unicode__(self):
return self.name
def get_choices(self):
choices = Choice.objects.filter(Question = self).order_by('id')
if len(choices) == 0:
return []
return choices

class Choice(models.Model):
name = generic.GenericRelation(Trans)
question = models.ForeignKey(Question)
nr = models.IntegerField()
def __unicode__(self):
return self.name

I have other necessary models too, but i think they are irrelevant
here.

The point of it is that, when i change website language (which now
works thanks to fixing urlconf in my previous thread), i get poll,
with all its questions/choices, in different language.

What i have not been able to figure out is how to change admin view in
a way that when i open poll (for adding a new one)it loops through
languages and gives me X fields where to enter poll name (depending on
how many languages the site has).

Poll in admin.py is like this:

class PollAdmin(admin.ModelAdmin):
list_display = ('name', 'pub_date', 'was_published_today')

and when i go to poll section in admin i get field for publishing date
and thats it. As it seems i lack understanding in several areas : how
to set up admin view so i can set necessary fields and how to use
those generic relations and i have even have created models in a way
that i must create them if i want to achieve my goals.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



[Django Admin + Generic Relations] ManyToMany Model Inline?

2009-03-30 Thread Liquidrums

In the documentation for Generic Relations, a Vegetable and Animal can
be Tagged via a GenericInline for each model.

I want to be able to choose a tag and subsequently add/remove which
models have that tag via a ManyToMany-style inline.

Is this already available, or do I have to roll my own?  I want to
have fine-grained control over what a tag points to, rather than
editing each separate model on its own & remove that tag.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



Re: Values from Reverse Generic Relations on multiple objects

2009-03-10 Thread Daniel Roseman

On Mar 10, 7:50 pm, Adam Nelson <a...@varud.com> wrote:
> http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#revers...
>
> I'm working with Reverse Generic Relations and I was wondering if
> there is a way to get the related objects for multiple objects in a
> simple way.  For instance, based on the bookmark example of that link,
> I'd like to do the following:
>
> >>> b.objects.filter(pk__in=[1,2])
> >>> b.tags.all()
>
> *** AttributeError: 'QuerySet' object has no attribute 'tags'
>
> First off, it's an annoying error because it should say something like
> 'more than one object b'.  Anyway, I can iterate through each b and
> then get the tags for that b and then put them back together again.
> Is there a simpler way to do this (i.e. get all tags for more than one
> bookmark)?
>
> Thanks.

You can't do it directly, but something like this should work:

bookmark_type = ContentType.objects.get_for_model(Bookmark)
TaggedItem.objects.filter(content_type=bookmark_type, object_id__in=
[1,2])
--
DR.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



Values from Reverse Generic Relations on multiple objects

2009-03-10 Thread Adam Nelson

http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#reverse-generic-relations

I'm working with Reverse Generic Relations and I was wondering if
there is a way to get the related objects for multiple objects in a
simple way.  For instance, based on the bookmark example of that link,
I'd like to do the following:

>>> b.objects.filter(pk__in=[1,2])
>>> b.tags.all()
*** AttributeError: 'QuerySet' object has no attribute 'tags'

First off, it's an annoying error because it should say something like
'more than one object b'.  Anyway, I can iterate through each b and
then get the tags for that b and then put them back together again.
Is there a simpler way to do this (i.e. get all tags for more than one
bookmark)?

Thanks.

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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
-~--~~~~--~~--~--~---



'extra' modifier and generic relations

2008-12-05 Thread Julien Phalip

Hi,

I have an Event model which can have comments. Comments can be added
to any kind of objects so the Comment model uses a generic relation
via content types.

When displaying a list of events I would like to display the number of
comments for each event. To improve performance and limit the number
of queries I'd like to use the 'extra' queryset modifier, but is that
even possible? The fact that it uses a generic relation means that I
need to know the content type id. If I hardcode that id in the 'extra'
statement then the site cannot reliably be ported to another database.

Can the extra modifier be reliably used with generic relations, or is
there a workaround?

Thanks a lot for your advice.

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



Re: prepopulated_fields with generic relations

2008-08-26 Thread Donovan

Oops, correct here:

class Content(models.Model):
seo_urls = generic.GenericRelation(SeoUrl)
def get_absolute_url(self):
return ('/%s/' % self.seo_urls.order_by('priority')[0].seotitle)

On 25 Aug, 23:04, Donovan <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I am trying to get this model and admin declaration working:
>
> #models.py
>
> class SeoUrl(models.Model):
>         seotitle = models.SlugField(max_length = 100)
>         priority = models.PositiveIntegerField(blank=False, null=False)
>
>         content_type = models.ForeignKey(ContentType)
>         object_id = models.PositiveIntegerField()
>         content_object = generic.GenericForeignKey('content_type',
> 'object_id')
>
> class Content(models.Model):
>         seo_urls = generic.GenericRelation(SeoUrl)
>         def get_absolute_url(self):
>                 return ('/%s/' % self.seo_urls[0])
>
>         class Meta:
>                 abstract = True
>
> class Author(Content):
>         firstname = models.CharField(max_length = 1000)
>         lastname = models.CharField(max_length = 1000)
>
> #admin.py
>
> class SeoUrlInline(generic.GenericStackedInline):
>         model = SeoUrl
>
> class AuthorAdmin(admin.ModelAdmin):
>         inlines = [ SeoUrlInline,]
>        prepopulated_fields= {'seotitle':("firstname", "lastname",) } #This
> line should pre-populate the first seo_url
>
> I want the firstinlineof SeoUrl to be populated when the user types
> something in to the firstname and lastname fields. The last line of
> AuthorAdmin is the problem. It causes this error:
>
> `AuthorAdmin.prepopulated_fields` refers to field `seotitle` that is
> missing from model `Author`.
>
> which is correct! Is there a way to make this possible? I know I could
> resort to some jQuery and admin template modification, but was
> wondering if the prepopulate_fields code has some awareness of the
> eventual id's ofinlineform fields.
>
> Cheers in advance,
> Donovan.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



prepopulated_fields with generic relations

2008-08-25 Thread Donovan

Hi,

I am trying to get this model and admin declaration working:

#models.py

class SeoUrl(models.Model):
seotitle = models.SlugField(max_length = 100)
priority = models.PositiveIntegerField(blank=False, null=False)

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

class Content(models.Model):
seo_urls = generic.GenericRelation(SeoUrl)
def get_absolute_url(self):
return ('/%s/' % self.seo_urls[0])

class Meta:
abstract = True

class Author(Content):
firstname = models.CharField(max_length = 1000)
lastname = models.CharField(max_length = 1000)


#admin.py

class SeoUrlInline(generic.GenericStackedInline):
model = SeoUrl

class AuthorAdmin(admin.ModelAdmin):
inlines = [ SeoUrlInline,]
prepopulated_fields = {'seotitle':("firstname", "lastname",) } #This
line should pre-populate the first seo_url

I want the first inline of SeoUrl to be populated when the user types
something in to the firstname and lastname fields. The last line of
AuthorAdmin is the problem. It causes this error:

`AuthorAdmin.prepopulated_fields` refers to field `seotitle` that is
missing from model `Author`.

which is correct! Is there a way to make this possible? I know I could
resort to some jQuery and admin template modification, but was
wondering if the prepopulate_fields code has some awareness of the
eventual id's of inline form fields.

Cheers in advance,
Donovan.


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



Re: generic relations

2008-06-06 Thread M.Ganesh

Filippo Santovito wrote:
> Hi all,
> I've read http://www.djangoproject.com/documentation/models/generic_relations/
> .
> How can I share a tag between Animal and Vegetables?
>
>   
have a look at http://code.google.com/p/django-tagging/

Ganesh


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



generic relations

2008-06-04 Thread Filippo Santovito

Hi all,
I've read http://www.djangoproject.com/documentation/models/generic_relations/
.
How can I share a tag between Animal and Vegetables?

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



Generic relations - reasonable usage?

2007-10-22 Thread David Reynolds

Hi,

I have the requirement to have an active/inactive function for all  
contenttypes in a site I'm working on. Is this a valid usage for a  
Generic Relationship?

If so, any tips as to how I'd go about implementing this?

Thanks,

David

-- 
David Reynolds
[EMAIL PROTECTED]



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



Re: Stuck on generic relations

2007-10-11 Thread Doug B

Anwering my own question... it helps to specify an actual join
condition.

This worked:
extra['last_event_when'] = "SELECT event_loggedevent.when FROM
event_loggedevent,event_eventrelation WHERE
(event_eventrelation.event_id = event_loggedevent.id) AND
(event_eventrelation.content_type_id = %s) AND
(event_eventrelation.object_id = common_idxlead.id) ORDER BY
event_loggedevent.when DESC limit 1" % ct

... off to amazon to look for a decent sql book so I can avoid asking
silly questions in the future.


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



Stuck on generic relations

2007-10-11 Thread Doug B

I have a page that needs to display basic user information plus the
last logged activity date for the user, and I need to be able to sort
by that value. (there are two of these relations,I'm just mentioning
one here)  My SQL-fu is very, very weak and I just can't seem to get
it.

There is a table in the middle that is kind of like a many to many,
but with a generic foreign key on one side, EventRelation.  That has
the content_type and object_id values for user, and a normal
foreignkey into the LoggedEvent model that has the field I need.

class LoggedEvent(models.Model):
 when = models.DateTimeField()
 summary = models.CharField(maxlength=255,null=True)
 

class EventRelation(models.Model):
event = models.ForeignKey('LoggedEvent')
objects=generic_relations.GenericManager()
content_type = models.ForeignKey(ContentType,null=True,blank=True)
object_id = models.PositiveIntegerField(null=True,blank=True)
obj = models.GenericForeignKey()

I've tried using extra, but what I thought might work just grabs the
latest event by any user, not the latest event per user (idxlead
model).  If I could apply that select to each user, that is exactly
what I think I'm looking for:

extra['last_event_when'] = "SELECT event_loggedevent.when FROM
event_loggedevent,event_eventrelation WHERE
((event_eventrelation.object_id = common_idxlead.id) AND
(event_eventrelation.content_type_id = %s)) ORDER BY
event_loggedevent.when DESC limit 1" % ct

ct is the contenttype pk for the idxlead model.

There are quite a few users (25,000), and a lot more events.  I
thought about adding a field on the user model and updating that on
each event, but I was worried about an extra write on almost every
request.  I'd appreciate any suggestions.


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



Re: cascading delete and generic relations

2007-08-07 Thread Jonathan Wood



On Aug 1, 12:30 pm, Jonathan Wood <[EMAIL PROTECTED]> wrote:

>
> Do I need to somehow clean up the "test_group_perms" table when Ideletea 
> subject? Or am I coding my modules incorrectly?

Followup:

After a bit more digging, it looks like Django is not emulating
cascading deletes properly here (SQLite does not support foreign key
constraints so it is up to either my code or Django to do it). We have
implemented some code suggested on the SQLite wiki [1] to maintain
relational integrity, and things are working now.

Jon

[1] http://www.sqlite.org/cvstrac/wiki?p=ForeignKeyTriggers


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



cascading delete and generic relations

2007-08-01 Thread Jonathan Wood

I think I am confused about how to use generic relations properly -
when I delete something, cascading delete is not happening as
expected.

Here are my models:

class Permission(models.Model):
name = models.CharField(maxlength=32)
content_type = models.ForeignKey(ContentType, null=True)
object_id = models.PositiveIntegerField(null=True)
content_object = generic.GenericForeignKey()

class Subject(models.Model):
name = models.CharField(maxlength=32)
perms = generic.GenericRelation(Permission)

class Group(models.Model):
name = models.CharField(maxlength=32)
perms = models.ManyToManyField(Permission, null=True)

(The goal is that a group can have permissions, and each permission
pertains to a subject object, but the subject object can be one of
many different types.)

In my test scenario, I add two subjects (s1 and s2), two permissions
referring to these subjects (p1->s1, p2->s2), and one group (g1) that
is assigned both permissions. So far so good.

When I delete the second subject (s2), things mostly happen as
expected:
  Subject.objects.all() shows only s1
  Permission.objects.all() shows only p1
  g1.perms.all() shows only p1

However, the database table that contains the relationships between
Group and Permission still has rows for both permissions (shown using
sqlite3 and .dump):

CREATE TABLE "test_group_perms" (
"id" integer NOT NULL PRIMARY KEY,
"group_id" integer NOT NULL REFERENCES "test_group" ("id"),
"permission_id" integer NOT NULL REFERENCES
"test_permission" ("id"),
UNIQUE ("group_id", "permission_id")
);
INSERT INTO "test_group_perms" VALUES(1, 1, 1);
INSERT INTO "test_group_perms" VALUES(2, 1, 2);
CREATE INDEX "test_permission_content_type_id" ON
"test_permission" ("content_type_id");
COMMIT;

This seems mostly harmless, except that when I create a new subject
(s3) and associate it with a new permission (p3), my group g1 now has
permission p3 even though it was never explicitly assigned that
permission:

>>> g1.perms.all()
[, ]

Do I need to somehow clean up the "test_group_perms" table when I
delete a subject? Or am I coding my modules incorrectly?

I am using the SVN version of Django trunk, updated 7/31/2007.

Thanks for any help!
Jon


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



Re: Generic Relations + Admin Interface

2007-07-03 Thread Russell Keith-Magee

On 7/4/07, David <[EMAIL PROTECTED]> wrote:
>
> Please let me stress that that isn't the full implementation (if you
> want me to go into further detail, please let me know). Basically, I
> want to be able to assign many different objects (of different model
> types) to an Article.  I need to be able to do this via the Admin
> interface in a user friendly way so that the people who write the
> articles can do it easily.
>
> The way I had this working in Rails was with a fancy controller method
> and some Ajax.

As you have noticed, there is limited support for generic relations in
the admin view at the moment.  We are in the process of rewriting the
admin view to make it easier to customize, and to use the new forms
framework.

Ticket #4667 (http://code.djangoproject.com/ticket/4667) contains a
patch that extends the newforms-admin branch to support edit-inline
for generic relations. I haven't looked at this code, but Honza Král
is fairly reliable contributor. I'd be interested in hearing any
feedback on this patch.

Yours,
Russ Magee %-)

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



Re: Generic Relations + Admin Interface

2007-07-03 Thread Wiley

I posted about the exact same issue a couple days ago and someone
suggested using the js attribute of the admin class.  Unfortunately as
a novice programmer this is going to take me a while to navigate so
I've moved on to other areas of my application before I get down into
it.  I'm watching this thread with eager interest however, in case
someone has a magic solution.

I'm also new to open source software communities, so I don't exactly
know the appropriate venue for feature requests, but the feature that
David is describing here strikes me as tremendously useful.  Are other
people wishing that this existed in Django?

On Jul 4, 5:05 am, David <[EMAIL PROTECTED]> wrote:
> I was really excited about Rails. But however much it claims that it
> follows the DRY convention, I unfortunately do find myself repeating
> myself for things like the admin area of my site.
>
> That's why the Admin interface of Django has now become ever so much
> more appealing to me. Having spent a whole day looking into Django,
> looks like it has everything I need to port my application over.
>
> I started with my basic models, and they all works marvellously.
> However, when I come to trying to implement the hardest feature in my
> Rails app, a many-to-many polymorphic association (generic relation in
> Django speak), I've hit the only hurdle stopping me from reaching the
> finishing line.
>
> I have my models (simplified here for this posting):
>
> from django.contrib.contenttypes.models import ContentType
> from django.contrib.contenttypes import generic
>
> class Article(models.Model):
> title = models.CharField(maxlength=300)
> ...
>
> class Assignable(models.Model):
> article = models.ForeignKey(Article)
> content_type = models.ForeignKey(ContentType)
> object_id = models.PositiveIntegerField()
> content_object = generic.GenericForeignKey()
>
> class Character(models.Model):
> name = models.CharField(maxlength=50)
>
> articles = generic.GenericRelation(Article)
>
> class Film(models.Model):
> title = models.CharField(maxlength=50)
>
> characters = models.ManyToManyField(Character)
> articles = generic.GenericRelation(Article)
>
> Please let me stress that that isn't the full implementation (if you
> want me to go into further detail, please let me know). Basically, I
> want to be able to assign many different objects (of different model
> types) to an Article.  I need to be able to do this via the Admin
> interface in a user friendly way so that the people who write the
> articles can do it easily.
>
> The way I had this working in Rails was with a fancy controller method
> and some Ajax.
>
> For the Admin interface for the Articles, I basically want to be able
> to have inline editing for adding new 'Assignables' (objects of
> different model types). It would basically be two select boxes. The
> first would contain the models that have a generic relation to the
> Article model. Upon selecting one of those models, the second select
> box is populated with the objects of that model type. You can then
> assign that object to the Article. And you can assign as many objects
> as you like to an Article.
>
> Like I say, this is the one thing preventing me from moving over to
> Django, and I'm so close!! It's torture. I really hate having to spend
> all day coding the admin part of my Rails app, when I can do 80% of it
> in Django in around 2 lines per model!!
>
> Surely other people need this as well?  Has anyone found a solution?
>
> Any help, direction or guidance would be very much appreciated.


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



Generic Relations + Admin Interface

2007-07-03 Thread David

I was really excited about Rails. But however much it claims that it
follows the DRY convention, I unfortunately do find myself repeating
myself for things like the admin area of my site.

That's why the Admin interface of Django has now become ever so much
more appealing to me. Having spent a whole day looking into Django,
looks like it has everything I need to port my application over.

I started with my basic models, and they all works marvellously.
However, when I come to trying to implement the hardest feature in my
Rails app, a many-to-many polymorphic association (generic relation in
Django speak), I've hit the only hurdle stopping me from reaching the
finishing line.

I have my models (simplified here for this posting):

from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Article(models.Model):
title = models.CharField(maxlength=300)
...

class Assignable(models.Model):
article = models.ForeignKey(Article)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()

class Character(models.Model):
name = models.CharField(maxlength=50)

articles = generic.GenericRelation(Article)

class Film(models.Model):
title = models.CharField(maxlength=50)

characters = models.ManyToManyField(Character)
articles = generic.GenericRelation(Article)

Please let me stress that that isn't the full implementation (if you
want me to go into further detail, please let me know). Basically, I
want to be able to assign many different objects (of different model
types) to an Article.  I need to be able to do this via the Admin
interface in a user friendly way so that the people who write the
articles can do it easily.

The way I had this working in Rails was with a fancy controller method
and some Ajax.

For the Admin interface for the Articles, I basically want to be able
to have inline editing for adding new 'Assignables' (objects of
different model types). It would basically be two select boxes. The
first would contain the models that have a generic relation to the
Article model. Upon selecting one of those models, the second select
box is populated with the objects of that model type. You can then
assign that object to the Article. And you can assign as many objects
as you like to an Article.

Like I say, this is the one thing preventing me from moving over to
Django, and I'm so close!! It's torture. I really hate having to spend
all day coding the admin part of my Rails app, when I can do 80% of it
in Django in around 2 lines per model!!

Surely other people need this as well?  Has anyone found a solution?

Any help, direction or guidance would be very much appreciated.


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



Re: One-to-one relationship (model inheritance) or generic relations?

2007-06-29 Thread Jamie Pittock

Russ,

Really useful response, thanks.

I had thought about your third option but as I figured there'd be a
lot of empty fields I didn't give it much consideration.  I might
actually go down that route until I have a better understanding of
generic relations.

Thanks again.
j.

On Jun 29, 2:20 am, "Russell Keith-Magee" <[EMAIL PROTECTED]>
wrote:
> On 6/28/07, Jamie Pittock <[EMAIL PROTECTED]> wrote:
>
>
>
> > I don't want to code myself into a corner, so when I start looking at
> > features such as allowing users to search all venues would I be best
> > with one parent model or will I be ok keeping them separate?   The
> > different types of venues have quite a number of different attributes
> > btw which is why they are different models rather than simply
> > categoried.
>
> Model inheritance sounds good on paper, but in practice, it gets
> somewhat inconvenient - lots of table joins to get at basic
> attributes, etc. If you have very few common attributes anyway,
> generic relations are probably worth investigation.
>
> However, as always, YMMV. My only reservation in recommending generic
> relations is that they aren't fully integrated with admin yet (though
> there is a patch floating around to integrate them with
> newforms-admin), and they're not fully documented. However, if you're
> willing to put up with those limitations, it sounds like they could be
> a good match for your needs.
>
> A third approach that you haven't mentioned is to have a single
> 'object' table that is sparse; i.e., instead of
>
> class Bar(Model):
>name = CharField()
>number_of_bartenders = IntegerField()
>
> class Club(Model):
>name = CharField()
>music_style = CharField()
>
> you have a single model that has all the fields:
>
> class Venue(Model):
>name = CharField()
>venuetype = CharField(choices=(('b','bar'),('c','club'))
>number_of_bartenders = IntegerField(null=True)
>music_style = CharField(null=True)
>
> This way you spend a little more time in data validation (making sure
> that you have all the columns that you need for any given row), and
> you waste a little space in the database, but lookups will be a little
> faster (as no joins are required).
>
> Yours,
> Russ Magee %-)


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



Re: One-to-one relationship (model inheritance) or generic relations?

2007-06-28 Thread Russell Keith-Magee

On 6/28/07, Jamie Pittock <[EMAIL PROTECTED]> wrote:
>
> I don't want to code myself into a corner, so when I start looking at
> features such as allowing users to search all venues would I be best
> with one parent model or will I be ok keeping them separate?   The
> different types of venues have quite a number of different attributes
> btw which is why they are different models rather than simply
> categoried.

Model inheritance sounds good on paper, but in practice, it gets
somewhat inconvenient - lots of table joins to get at basic
attributes, etc. If you have very few common attributes anyway,
generic relations are probably worth investigation.

However, as always, YMMV. My only reservation in recommending generic
relations is that they aren't fully integrated with admin yet (though
there is a patch floating around to integrate them with
newforms-admin), and they're not fully documented. However, if you're
willing to put up with those limitations, it sounds like they could be
a good match for your needs.

A third approach that you haven't mentioned is to have a single
'object' table that is sparse; i.e., instead of

class Bar(Model):
   name = CharField()
   number_of_bartenders = IntegerField()

class Club(Model):
   name = CharField()
   music_style = CharField()

you have a single model that has all the fields:

class Venue(Model):
   name = CharField()
   venuetype = CharField(choices=(('b','bar'),('c','club'))
   number_of_bartenders = IntegerField(null=True)
   music_style = CharField(null=True)

This way you spend a little more time in data validation (making sure
that you have all the columns that you need for any given row), and
you waste a little space in the database, but lookups will be a little
faster (as no joins are required).

Yours,
Russ Magee %-)

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



One-to-one relationship (model inheritance) or generic relations?

2007-06-28 Thread Jamie Pittock

I'm still new to Django so bear with me ;)

I have models for different types of venues (Bars, Clubs, etc).
Because for example, I'd like to use one Rating model across all these
venue Models I'd presumed that I'd need a parent Venue Model, using
some kind of one-to-one relationship (until model inheritance is
reintroduced), so that each venue had a unique primary key that could
be related to the rating.

However, apps such as comment and tagging get away with it.  Is this
through Generic Relations?

I don't want to code myself into a corner, so when I start looking at
features such as allowing users to search all venues would I be best
with one parent model or will I be ok keeping them separate?   The
different types of venues have quite a number of different attributes
btw which is why they are different models rather than simply
categoried.

Any clarification much appeciated.


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



Re: relation-spanning lookups with generic relations?

2007-06-17 Thread [EMAIL PROTECTED]

It seems like it would make more sense to do something like:
TaggedItem.objects.filter(book__writer="Dostoevsky")

Unfortunately it looks like this constructs faulty SQL (the join
statement in particular), although it appears like it _should_ work.
Just try TaggedItem.objects.filter(alskdfjladf='dog') and you'll see
that it tells you that books (among other generic relations made by
TaggedItem) is one of the fields it suggests to span across.

Going to post a separate question about this after I try to see if
this topic has been discussed in these groups, but I'd say this is the
cleanest and most intuitive approach.

On May 28, 9:53 am, "Jonathan Buchanan" <[EMAIL PROTECTED]>
wrote:
> On 5/28/07, Bram - Smartelectronix <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > Hi there,
>
> > Say I have:
>
> > class TaggedItem(models.Model):
> >  """A tag on an item."""
> >  tag = models.SlugField()
> >  content_type = models.ForeignKey(ContentType)
> >  object_id = models.PositiveIntegerField()
>
> >  content_object = models.GenericForeignKey()
>
> >  class Meta:
> >  ordering = ["tag"]
>
> >  def __str__(self):
> >  return self.tag
>
> > class Book(models.Model):
> >  writer = models.ForeignKey(User)
> >  tags = models.GenericRelation(TaggedItem)
>
> > How do I get all Tags for books by Dostoevsky ? :-)
>
> > TaggedItem.objects.filter(content_type=ContentType.objects.get_for_model(Book),
> > content_object__writer="Dostoevsky")
>
> > ...doesn't work... And
>
> > TaggedItem.objects.filter(content_type=ContentType.objects.get_for_model(Book),
> > object_id__in=[ book.id for book in
> > Book.objects.filter(writer="Dostoevsky")])
>
> > is pretty bad.
>
> > Should I be looking at extra( ) or is there a smarter way to go about this?
>
> >   - bram
>
> I've just implemented something like this in django-tagging, but it
> feels like a massive hack:
>
> Check out the usage_for_model method 
> inhttp://django-tagging.googlecode.com/svn/trunk/models.py
>
> It starts with a basic query template which will retrieve tags and
> usage counts for a particular model, taking a dictionary of field
> lookups as an optional argument. If this is provided, some of Django's
> query generation internals are used to generate required JOIN and
> WHERE statements to restrict the tags returned to a subset of the
> model.
>
> If anyone reading that immediately thinks "there's a much cleaner way
> to do that with the DB API, yuo buffoon", I'm all ears! :)
>
> Jonathan.


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



deleting rows with generic relations

2007-06-13 Thread Bram - Smartelectronix

hello everyone,


Say I have

Model1
Model2
Model3

And generic relations pointing to these...

Like, say, Comments or Tags

When deleting Model1, 2, 3 I obviously need to delete all the generic 
ones! Is there any smarter way to go about this except for overriding 
delete( ) and doing it by hand?

If there's a lot of models and a lot of generic relations, this becomes 
a bit of a pain... Add one more generic => change all delete's!


  - bram

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



Query-light retrieval of generic relations

2007-06-04 Thread Jonathan Buchanan

Hi all,

I'm trying to write a utility method to retrieve generically related 
content (the particular model I'm using has the standard ContentType FK, 
object id and GenericFK) without ending up with one database hit per object:

http://dpaste.com/11633/


from django.contrib.contenttypes.models import ContentType

def fetch_content_objects(item_queryset):
 """
 Populates the given items with their ContentTypes and content
 objects, grouping the retrieval of content objects by model type
 to reduce the number of queries executed.
 """
 items = list(item_queryset)

 # Group object ids by their content type ids
 objects_by_ctype = {}
 content_type_ids = set()
 for item in items:
 if not objects_by_ctype.has_key(item.content_type_id):
 objects_by_ctype[item.content_type_id] = []
 objects_by_ctype[item.content_type_id].append(item.object_id)
 content_type_ids.add(item.content_type_id)

 # Retrieve content types and content objects in bulk
 content_types = 
ContentType._default_manager.in_bulk(list(content_type_ids))
 for ctype_id, object_ids in objects_by_ctype.items():
 model = content_types[ctype_id].model_class()
 objects_by_ctype[ctype_id] = 
model._default_manager.in_bulk(object_ids)

 # Place content types and content objects in the appropriate items
 for item in items:
 item.content_type = content_types[item.content_type_id]
 item.object = 
objects_by_ctype[item.content_type_id][item.object_id]

 return items


So, I try to load and access the generic content for all the Items in my 
database at the moment (1744 of them at the moment). I can access the 
objects I've populated just fine without incurring any extra queries (12 
queries for 1744 objects. Woo! Yay!), but as soon as I try to access 
their content_type attributes...

http://dpaste.com/11634/


 >>> from jellyroll.managers import fetch_content_objects
 >>> from jellyroll.models import Item
 >>> from django.db import connection
 >>> items = fetch_content_objects(Item.objects.all())
 >>> len(connection.queries)
12
 >>> len(items)
1744
 >>> [item.object for item in items]
...
 >>> len(connection.queries)
12
 >>> [item.content_type for item in items]
...
 >>> len(connection.queries)
1756

...I'm back to one-query-per-instanceville.

I've poked about a bit in 
django.db.models.fields.related.ReverseSingleRelatedObjectDescriptor, 
and even tried setting the '_content_type_cache' attribute it will 
eventually check for first in this particular case, but to no avail.

Has anyone done much work on "manually" populating related data? Any 
ideas how I can prevent that database hit per instance happening when I 
access the content_type attribute?

Thanks,
Jonathan

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



Re: relation-spanning lookups with generic relations?

2007-05-28 Thread Jonathan Buchanan

On 5/28/07, Bram - Smartelectronix <[EMAIL PROTECTED]> wrote:
>
> Hi there,
>
>
>
> Say I have:
>
> class TaggedItem(models.Model):
>  """A tag on an item."""
>  tag = models.SlugField()
>  content_type = models.ForeignKey(ContentType)
>  object_id = models.PositiveIntegerField()
>
>  content_object = models.GenericForeignKey()
>
>  class Meta:
>  ordering = ["tag"]
>
>  def __str__(self):
>  return self.tag
>
> class Book(models.Model):
>  writer = models.ForeignKey(User)
>  tags = models.GenericRelation(TaggedItem)
>
>
> How do I get all Tags for books by Dostoevsky ? :-)
>
> TaggedItem.objects.filter(content_type=ContentType.objects.get_for_model(Book),
> content_object__writer="Dostoevsky")
>
> ...doesn't work... And
>
> TaggedItem.objects.filter(content_type=ContentType.objects.get_for_model(Book),
> object_id__in=[ book.id for book in
> Book.objects.filter(writer="Dostoevsky")])
>
> is pretty bad.
>
>
> Should I be looking at extra( ) or is there a smarter way to go about this?
>
>
>   - bram

I've just implemented something like this in django-tagging, but it
feels like a massive hack:

Check out the usage_for_model method in
http://django-tagging.googlecode.com/svn/trunk/models.py

It starts with a basic query template which will retrieve tags and
usage counts for a particular model, taking a dictionary of field
lookups as an optional argument. If this is provided, some of Django's
query generation internals are used to generate required JOIN and
WHERE statements to restrict the tags returned to a subset of the
model.

If anyone reading that immediately thinks "there's a much cleaner way
to do that with the DB API, yuo buffoon", I'm all ears! :)

Jonathan.

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



relation-spanning lookups with generic relations?

2007-05-28 Thread Bram - Smartelectronix

Hi there,



Say I have:

class TaggedItem(models.Model):
 """A tag on an item."""
 tag = models.SlugField()
 content_type = models.ForeignKey(ContentType)
 object_id = models.PositiveIntegerField()

 content_object = models.GenericForeignKey()

 class Meta:
 ordering = ["tag"]

 def __str__(self):
 return self.tag

class Book(models.Model):
 writer = models.ForeignKey(User)
 tags = models.GenericRelation(TaggedItem)


How do I get all Tags for books by Dostoevsky ? :-)

TaggedItem.objects.filter(content_type=ContentType.objects.get_for_model(Book), 
content_object__writer="Dostoevsky")

...doesn't work... And

TaggedItem.objects.filter(content_type=ContentType.objects.get_for_model(Book), 
object_id__in=[ book.id for book in 
Book.objects.filter(writer="Dostoevsky")])

is pretty bad.


Should I be looking at extra( ) or is there a smarter way to go about this?


  - bram

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



Re: Generic relations naming

2007-05-21 Thread James Bennett

On 5/21/07, Sebastjan Trepca <[EMAIL PROTECTED]> wrote:
> I just started to use generic relations and I was wondering why are the
> default field names "object_id" and "content_type" and not "object_id" and
> "object_type"?
> Seems better that way and more logical ... or is it?

I would guess that the "content_type" field is given that name because
it's a foreign key to the ContentType model in
django.contrib.contenttypes.

-- 
"Bureaucrat Conrad, you are technically correct -- the best kind of correct."

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



Generic relations naming

2007-05-21 Thread Sebastjan Trepca
Hi,

I just started to use generic relations and I was wondering why are the
default field names "object_id" and "content_type" and not "object_id" and
"object_type"?
Seems better that way and more logical ... or is it?

Thanks, Sebastjan

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



Re: fixtures for generic relations?

2007-05-19 Thread Malcolm Tredinnick

On Sat, 2007-05-19 at 13:11 +0200, Bram - Smartelectronix wrote:
> Russell Keith-Magee wrote:
> >> how do I -in fixtures- explain a variable needs to come from another table?
> >> I don't want to write "content_type: 15" as elsewhere!
> > 
> > That's the way its done. GenericRelation is a convenience wrapper
> > around the content type and object id database entries; you need to
> > provide values for those two columns, and they're both specified as
> > integers.
> 
> True, but right now I have the initial_data written as:
> 
> INSERT INTO ... VALUES ((select id from django_content_type where name = 
> 'profile'), ..);
> 
> Which stays OK, even if I add/remove Models (which change the 
> content_type table content!)
> 
> > There has been some talk recently about establishing a common
> > interface for datatype coercion; providing a more natural interface
> > for datatype deserialization is one possible use case for coercion of
> > this type. However, there hasn't been any decisions made as yet. If
> > you want to make a suggestion, feel free to join into the discussion
> > on django-dev.
> 
> What about letting users use python scripts to generate the initial data 
> (if really needed/wanted)?
> 
> -
> 
> json = """
> [
>{
>  content_type: {{profile_contenttype.id}}
>}
>// more regular json goes here
> ]
> """
> 
> from django.template import Context, Template
> from django.contrib.contenttypes.models import ContentType
> 
> def get_json():
>c = Context({'profile_content_type': ContentType.objects.get.})
>t = Template(json )
>return t.render(c)
> 
> -
> 
> 
> I know that this kind of goes against what fixtures should be, but it 
> would be pretty flexible...

You can already do this as part of your test setup. Tests are just
Python files, after all, so you can do whatever extra customisation you
like in there.

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 django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: fixtures for generic relations?

2007-05-19 Thread Bram - Smartelectronix

Russell Keith-Magee wrote:
>> how do I -in fixtures- explain a variable needs to come from another table?
>> I don't want to write "content_type: 15" as elsewhere!
> 
> That's the way its done. GenericRelation is a convenience wrapper
> around the content type and object id database entries; you need to
> provide values for those two columns, and they're both specified as
> integers.

True, but right now I have the initial_data written as:

INSERT INTO ... VALUES ((select id from django_content_type where name = 
'profile'), ..);

Which stays OK, even if I add/remove Models (which change the 
content_type table content!)

> There has been some talk recently about establishing a common
> interface for datatype coercion; providing a more natural interface
> for datatype deserialization is one possible use case for coercion of
> this type. However, there hasn't been any decisions made as yet. If
> you want to make a suggestion, feel free to join into the discussion
> on django-dev.

What about letting users use python scripts to generate the initial data 
(if really needed/wanted)?

-

json = """
[
   {
 content_type: {{profile_contenttype.id}}
   }
   // more regular json goes here
]
"""

from django.template import Context, Template
from django.contrib.contenttypes.models import ContentType

def get_json():
   c = Context({'profile_content_type': ContentType.objects.get.})
   t = Template(json )
   return t.render(c)

-


I know that this kind of goes against what fixtures should be, but it 
would be pretty flexible...


  - bram

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



Re: fixtures for generic relations?

2007-05-18 Thread Russell Keith-Magee

On 5/18/07, Bram - Smartelectronix <[EMAIL PROTECTED]> wrote:
>
> hi everyone,
>
>
> how do I -in fixtures- explain a variable needs to come from another table?
>
> I don't want to write "content_type: 15" as elsewhere!

That's the way its done. GenericRelation is a convenience wrapper
around the content type and object id database entries; you need to
provide values for those two columns, and they're both specified as
integers.

There has been some talk recently about establishing a common
interface for datatype coercion; providing a more natural interface
for datatype deserialization is one possible use case for coercion of
this type. However, there hasn't been any decisions made as yet. If
you want to make a suggestion, feel free to join into the discussion
on django-dev.

Yours,
Russ Magee %-)

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



fixtures for generic relations?

2007-05-18 Thread Bram - Smartelectronix

hi everyone,


how do I -in fixtures- explain a variable needs to come from another table?

I don't want to write "content_type: 15" as elsewhere!


  - bram

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



generic relations for auth.User instead of myapp.UserProfile?

2007-01-19 Thread Bram - Smartelectronix


Hello everyone,


currently we have a working UserProfile, working with the auth.User. 
Now, we plenty of things in this profile (tags, favorites, the usual 
social networking blah ;-)), and we would really like to move them to 
User as the rest of the models all refer to User!


So, there's Article.user but if we want tags, it's 
Article.user.get_profile which is a pitty.


This works at the command line:

User.tags = 
Tag.objects.filter(content_type=ContentType.objects.get_for_model(User))


User.comments = 
Tag.objects.filter(content_type=ContentType.objects.get_for_model(User))


etc

But is there a way to patch User (without editing it's source of course) 
to have these always? And, is it a good idea?



thanks a lot for any ideas!


 - bram

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



Re: Generic relations in admin proposal

2006-12-19 Thread zenx

It's not my code, just took a look at it and found it useful.

Thank you for looking at it!

zenx


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



Re: Generic relations in admin proposal

2006-12-18 Thread Jacob Kaplan-Moss

On 12/18/06 6:24 PM, zenx wrote:
> After finding a good solution for generic relations in admin:
> http://net-x.org/weblog/2006/nov/29/django-generic-relations-made-easier/
> 
> I think that it should be implemented in the admin app of the django
> development version.
> 
> What do you think about it? Want django developers to take the app as
> basis for generic relations in admin?

I'll take a look.

FYI, if you've got code to contribute to Django, the best place to post about 
it is to django-dev; I and the other developers read posts over there more 
carefully, and so your post is likely to get more attention.

Anyway, though, I'll look at your code and post about it on django-dev if it 
needs following-up.

Thanks!

Jacob

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



Generic relations in admin proposal

2006-12-18 Thread zenx

Hi,

After finding a good solution for generic relations in admin:
http://net-x.org/weblog/2006/nov/29/django-generic-relations-made-easier/

I think that it should be implemented in the admin app of the django
development version.

What do you think about it? Want django developers to take the app as
basis for generic relations in admin?

thanks


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



Re: generic relations in the admin interface

2006-07-06 Thread va:patrick.kranzlmueller

sounds a bit complicated: save first, go back to the entry, add  
tag ... not sure if that works for me.
I´ll check out your scripts later.

for now, I´ll stick with many-to-many ...

thanks for your answer,

patrick


Am 06.07.2006 um 15:31 schrieb Jay Parlar:

>
> On 7/6/06, va:patrick.kranzlmueller <[EMAIL PROTECTED]> wrote:
>>
>> just tested generic relations for tagging.
>> to my surprise, there´s no possibility to enter tags (for my blog-
>> entries) in the admin interface.
>>
>> however, i do get additional user permissions:  "can add tagged
>> item", ...
>> did I miss something?
>
> There's not been any explicit Admin support added for generic  
> relations, yet.
>
> The extra permission is automatically added for anything in your  
> model.
>
> My solution to generic relations and the admin is to use some custom
> JavaScript. What happens is I'll add, for example, a blog entry. Once
> that's entered and saved, anytime I go to that entry in the admin, I
> have a link pop up that says "Add Tag for this item".
>
> That link then takes me to a TaggedItem page, and pre-populates the
> content_type and object_id fields. So all I have to do myself is
> provide the tag.
>
> You can see my javascript here:
> http://svn.jayparlar.com/website/trunk/jayparlar/site_media/js/
> And my blog and tags apps are found here:
> http://svn.jayparlar.com/website/trunk/jayparlar/
>
> Don't laugh at my JavaScript too much, I'm still just learning it.
>
> This is certainly not an ideal solution, but it's the best I could
> come up with for now.
>
> Jay P.
>
> >


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



Re: generic relations in the admin interface

2006-07-06 Thread Jay Parlar

On 7/6/06, va:patrick.kranzlmueller <[EMAIL PROTECTED]> wrote:
>
> just tested generic relations for tagging.
> to my surprise, there´s no possibility to enter tags (for my blog-
> entries) in the admin interface.
>
> however, i do get additional user permissions:  "can add tagged
> item", ...
> did I miss something?

There's not been any explicit Admin support added for generic relations, yet.

The extra permission is automatically added for anything in your model.

My solution to generic relations and the admin is to use some custom
JavaScript. What happens is I'll add, for example, a blog entry. Once
that's entered and saved, anytime I go to that entry in the admin, I
have a link pop up that says "Add Tag for this item".

That link then takes me to a TaggedItem page, and pre-populates the
content_type and object_id fields. So all I have to do myself is
provide the tag.

You can see my javascript here:
http://svn.jayparlar.com/website/trunk/jayparlar/site_media/js/
And my blog and tags apps are found here:
http://svn.jayparlar.com/website/trunk/jayparlar/

Don't laugh at my JavaScript too much, I'm still just learning it.

This is certainly not an ideal solution, but it's the best I could
come up with for now.

Jay P.

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



Re: generic relations in the admin interface

2006-07-06 Thread James Bennett

On 7/6/06, va:patrick.kranzlmueller <[EMAIL PROTECTED]> wrote:
> just tested generic relations for tagging.
> to my surprise, there´s no possibility to enter tags (for my blog-
> entries) in the admin interface.

The generic relations feature is extremely (it's only been in trunk a
week or two) and only partially implemented; at the moment there is no
support for it in the admin application.

-- 
"May the forces of evil become confused on the way to your house."
  -- George Carlin

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



generic relations in the admin interface

2006-07-06 Thread va:patrick.kranzlmueller

just tested generic relations for tagging.
to my surprise, there´s no possibility to enter tags (for my blog- 
entries) in the admin interface.

however, i do get additional user permissions:  "can add tagged  
item", ...
did I miss something?

code:

class TaggedItem(models.Model):
 """A tag on an item."""
 tag = models.SlugField()
 content_type = models.ForeignKey(ContentType)
 object_id = models.PositiveIntegerField()
 content_object = models.GenericForeignKey()

 class Meta:
 ordering = ["tag"]

 def __str__(self):
 return self.tag

class Entry(models.Model):
 ...
 tags = models.GenericRelation(TaggedItem)
 ...


thanks,
patrick




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



Re: Generic relations and tags

2006-06-27 Thread nkeric

Jay Parlar wrote:
> That's a pretty neat way to do it, I'm going to have to try it out. Do
> you use a ManyToManyField between your actual objects (like a blog
> Post, for instance) and the ObjectTag?
>
> Jay P.

hi Jay,

Since the ObjectTag model is the m2m table between the actual object
(which will be tagged) and the Tag model, so, you just add the
GenericRalation to you target object would be ok:

class Post(models.Model):
tags = models.GenericRelation(ObjectTag)

AFAIK, using the GenericForeignKey & GenericRelation does NOT create
any actual db tables or added any extra table fields, they've just
added a convenient way for easily access this kind of generic relation.
(let me know if I was wrong :)

you could simply remove the GenericForeignKey from the ObjectTag model
and remove the GenericRelation from the Post, then, via the
content_type & object_id fields of the ObjectTag, you can query for the
tags of a specific Post object by querying the ObjectTag & Tag table
together.

- Eric


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



Re: Generic relations and tags

2006-06-27 Thread Jay Parlar

On 6/27/06, Luke Plant <[EMAIL PROTECTED]> wrote:
>
> On Tuesday 27 June 2006 18:06, Jay Parlar wrote:
> > So I'm now trying the new generic relations out for tags, much like
> > the example in the documentation. The problem I'm having is doing a
> > filter() to get a QuerySet of tags with unique names. Any thoughts on
> > this?
> >
> > If two different objects are both given a tag "foo", there will be
> > two tags in the system that have 'foo' as their 'tag' value. The only
> > way I can think of doing this so far is to manually pull all the
> > results out of a QuerySet, and use Python to figure out all the
> > unique tag names.
>
> Would something like this do it?
>
> your_query_set.distinct().values('tag')


Oh wow, that seems to work perfectly.

Thanks,
Jay P.

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



Re: Generic relations and tags

2006-06-27 Thread Luke Plant

On Tuesday 27 June 2006 18:06, Jay Parlar wrote:
> So I'm now trying the new generic relations out for tags, much like
> the example in the documentation. The problem I'm having is doing a
> filter() to get a QuerySet of tags with unique names. Any thoughts on
> this?
>
> If two different objects are both given a tag "foo", there will be
> two tags in the system that have 'foo' as their 'tag' value. The only
> way I can think of doing this so far is to manually pull all the
> results out of a QuerySet, and use Python to figure out all the
> unique tag names.

Would something like this do it?

your_query_set.distinct().values('tag')

Luke


-- 
"Defeat: For every winner, there are dozens of losers.  Odds are you're 
one of them." (despair.com)

Luke Plant || L.Plant.98 (at) cantab.net || http://lukeplant.me.uk/

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



  1   2   >