Re: Model inheritance with optional self reference

2021-03-16 Thread wongX Ndeso
Just facing the same problem with you bro, and i ended up with proxy model
and using django-treebeard for the data hierarchy...


On Thu, 11 Mar 2021 at 17.47 Kunal Solanke 
wrote:

> Btw parts should be a m2m field ig.
>
> On Thu, Mar 11, 2021, 16:14 Kunal Solanke 
> wrote:
>
>> That's too hard of a problem statement for me,ig more experienced people
>> will be able to answer it more properly. But if its 99.99% I'd go with
>> whatever you have right now, rather than creating bunch or proxy models.
>>
>> On Thu, Mar 11, 2021, 16:06 Mateusz Wroblewski  wrote:
>>
>>> Hi All,
>>>
>>> does anybody have experience with the following data model and could
>>> advise which Django tools fit it best?
>>>
>>> Background:
>>> I have two types of Components (Core and Complex) that share many
>>> attributes and methods, but also have their own, specific data fields and
>>> methods.
>>>
>>> What complicates the design is the fact, that ComplexComponent might
>>> have CoreComponents assigned to it. A CoreComponent instance might be a
>>> "self-standing" entity without any relation to ComplexComponent, but there
>>> are also CoreComponents created only for the purpose of "building"
>>> ComplexComponents.
>>> ComplexComponent (although complex :) ) might (or might not) use
>>> CoreComponents in its structure ("complexity" comes then from a different,
>>> unrelated feature).
>>>
>>> 99.99% of the time I need to be able to handle instances of
>>> CoreComponent (self-standing entities) and instances of ComplexComponent
>>> (with their linked core components) separately in different views/areas of
>>> my application, however I can envision some special use cases where I would
>>> need to use aggregation on both types to return data for some dash board
>>> type of views (e.g. average cost of all components created this year).
>>> Also, when a ComplexComponent is handled/displayed in the view, I need
>>> to be able to access CoreComponents that "compose" it (if applicable).
>>>
>>> I'm trying to figure out what Django tools to use for modelling this
>>> setup and would be thankful to hear your take on that problem.
>>>
>>> My current setup uses base Component concrete model and
>>> CoreComponent/ComplexComponent deriving from it (and also being concrete
>>> models).
>>> I end up with three different tables. Having core components and complex
>>> components in separate tables seemed right initially, but I know this
>>> approach might be difficult to handle down the road, so I'm thinking about
>>> restructuring it and using e.g. Proxy models instead? If I rebuild these
>>> models now, I would prefer to do it "right".
>>>
>>> Does anybody have experience with a similar (the same?) design and could
>>> advise what would be the best tool in Django to implement this?
>>>
>>> Below a simplified view of the classes in scope (only for demonstration
>>> purpose).
>>>
>>> Many thanks for any feedback.
>>>
>>> Have a nice day!
>>>
>>> --
>>> 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 view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-users/36e6d27b-fd5d-4891-b999-0863a81ade85n%40googlegroups.com
>>> 
>>> .
>>>
>> --
> 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 view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CAOecAnwV_Zi3%3DdrUnUkChszUHktP13GO3fKkso1EA3QGjDKvjw%40mail.gmail.com
> 
> .
>

-- 
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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAJepfJXh0gdJF_OnQy0d5nEm89b7FLo%2BTy6-sK8U_f1x8kbFtw%40mail.gmail.com.


Re: Model inheritance with optional self reference

2021-03-11 Thread Kunal Solanke
Btw parts should be a m2m field ig.

On Thu, Mar 11, 2021, 16:14 Kunal Solanke 
wrote:

> That's too hard of a problem statement for me,ig more experienced people
> will be able to answer it more properly. But if its 99.99% I'd go with
> whatever you have right now, rather than creating bunch or proxy models.
>
> On Thu, Mar 11, 2021, 16:06 Mateusz Wroblewski  wrote:
>
>> Hi All,
>>
>> does anybody have experience with the following data model and could
>> advise which Django tools fit it best?
>>
>> Background:
>> I have two types of Components (Core and Complex) that share many
>> attributes and methods, but also have their own, specific data fields and
>> methods.
>>
>> What complicates the design is the fact, that ComplexComponent might have
>> CoreComponents assigned to it. A CoreComponent instance might be a
>> "self-standing" entity without any relation to ComplexComponent, but there
>> are also CoreComponents created only for the purpose of "building"
>> ComplexComponents.
>> ComplexComponent (although complex :) ) might (or might not) use
>> CoreComponents in its structure ("complexity" comes then from a different,
>> unrelated feature).
>>
>> 99.99% of the time I need to be able to handle instances of CoreComponent
>> (self-standing entities) and instances of ComplexComponent (with their
>> linked core components) separately in different views/areas of my
>> application, however I can envision some special use cases where I would
>> need to use aggregation on both types to return data for some dash board
>> type of views (e.g. average cost of all components created this year).
>> Also, when a ComplexComponent is handled/displayed in the view, I need to
>> be able to access CoreComponents that "compose" it (if applicable).
>>
>> I'm trying to figure out what Django tools to use for modelling this
>> setup and would be thankful to hear your take on that problem.
>>
>> My current setup uses base Component concrete model and
>> CoreComponent/ComplexComponent deriving from it (and also being concrete
>> models).
>> I end up with three different tables. Having core components and complex
>> components in separate tables seemed right initially, but I know this
>> approach might be difficult to handle down the road, so I'm thinking about
>> restructuring it and using e.g. Proxy models instead? If I rebuild these
>> models now, I would prefer to do it "right".
>>
>> Does anybody have experience with a similar (the same?) design and could
>> advise what would be the best tool in Django to implement this?
>>
>> Below a simplified view of the classes in scope (only for demonstration
>> purpose).
>>
>> Many thanks for any feedback.
>>
>> Have a nice day!
>>
>> --
>> 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 view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-users/36e6d27b-fd5d-4891-b999-0863a81ade85n%40googlegroups.com
>> 
>> .
>>
>

-- 
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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAOecAnwV_Zi3%3DdrUnUkChszUHktP13GO3fKkso1EA3QGjDKvjw%40mail.gmail.com.


Re: Model inheritance with optional self reference

2021-03-11 Thread Kunal Solanke
That's too hard of a problem statement for me,ig more experienced people
will be able to answer it more properly. But if its 99.99% I'd go with
whatever you have right now, rather than creating bunch or proxy models.

On Thu, Mar 11, 2021, 16:06 Mateusz Wroblewski  wrote:

> Hi All,
>
> does anybody have experience with the following data model and could
> advise which Django tools fit it best?
>
> Background:
> I have two types of Components (Core and Complex) that share many
> attributes and methods, but also have their own, specific data fields and
> methods.
>
> What complicates the design is the fact, that ComplexComponent might have
> CoreComponents assigned to it. A CoreComponent instance might be a
> "self-standing" entity without any relation to ComplexComponent, but there
> are also CoreComponents created only for the purpose of "building"
> ComplexComponents.
> ComplexComponent (although complex :) ) might (or might not) use
> CoreComponents in its structure ("complexity" comes then from a different,
> unrelated feature).
>
> 99.99% of the time I need to be able to handle instances of CoreComponent
> (self-standing entities) and instances of ComplexComponent (with their
> linked core components) separately in different views/areas of my
> application, however I can envision some special use cases where I would
> need to use aggregation on both types to return data for some dash board
> type of views (e.g. average cost of all components created this year).
> Also, when a ComplexComponent is handled/displayed in the view, I need to
> be able to access CoreComponents that "compose" it (if applicable).
>
> I'm trying to figure out what Django tools to use for modelling this setup
> and would be thankful to hear your take on that problem.
>
> My current setup uses base Component concrete model and
> CoreComponent/ComplexComponent deriving from it (and also being concrete
> models).
> I end up with three different tables. Having core components and complex
> components in separate tables seemed right initially, but I know this
> approach might be difficult to handle down the road, so I'm thinking about
> restructuring it and using e.g. Proxy models instead? If I rebuild these
> models now, I would prefer to do it "right".
>
> Does anybody have experience with a similar (the same?) design and could
> advise what would be the best tool in Django to implement this?
>
> Below a simplified view of the classes in scope (only for demonstration
> purpose).
>
> Many thanks for any feedback.
>
> Have a nice day!
>
> --
> 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 view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/36e6d27b-fd5d-4891-b999-0863a81ade85n%40googlegroups.com
> 
> .
>

-- 
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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAOecAnyLK2seCjbMrEtSj5KWqKEPmFNgDXoKw%3DUYU2PHwHfn6g%40mail.gmail.com.


Model inheritance with optional self reference

2021-03-11 Thread Mateusz Wroblewski
Hi All,

does anybody have experience with the following data model and could advise 
which Django tools fit it best?

Background:
I have two types of Components (Core and Complex) that share many 
attributes and methods, but also have their own, specific data fields and 
methods.

What complicates the design is the fact, that ComplexComponent might have 
CoreComponents assigned to it. A CoreComponent instance might be a 
"self-standing" entity without any relation to ComplexComponent, but there 
are also CoreComponents created only for the purpose of "building" 
ComplexComponents.
ComplexComponent (although complex :) ) might (or might not) use 
CoreComponents in its structure ("complexity" comes then from a different, 
unrelated feature).

99.99% of the time I need to be able to handle instances of CoreComponent 
(self-standing entities) and instances of ComplexComponent (with their 
linked core components) separately in different views/areas of my 
application, however I can envision some special use cases where I would 
need to use aggregation on both types to return data for some dash board 
type of views (e.g. average cost of all components created this year).
Also, when a ComplexComponent is handled/displayed in the view, I need to 
be able to access CoreComponents that "compose" it (if applicable).

I'm trying to figure out what Django tools to use for modelling this setup 
and would be thankful to hear your take on that problem.

My current setup uses base Component concrete model and 
CoreComponent/ComplexComponent deriving from it (and also being concrete 
models).
I end up with three different tables. Having core components and complex 
components in separate tables seemed right initially, but I know this 
approach might be difficult to handle down the road, so I'm thinking about 
restructuring it and using e.g. Proxy models instead? If I rebuild these 
models now, I would prefer to do it "right".

Does anybody have experience with a similar (the same?) design and could 
advise what would be the best tool in Django to implement this?

Below a simplified view of the classes in scope (only for demonstration 
purpose).

Many thanks for any feedback.

Have a nice day!

-- 
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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/36e6d27b-fd5d-4891-b999-0863a81ade85n%40googlegroups.com.


Re: Model Inheritance across apps

2016-09-29 Thread Mike Dewhirst

On 30/09/2016 10:33 AM, Malik Rumi wrote:

Assume two models, class Parent(models.Model): and Child(Parent):

Assume they are both in the same Project

Can Child be in a different app than Parent? In most cases the answer 
seems to be yes.


True. You only need to import Parent. But it might be better to put them 
both in their own app with Parent defined before Child.




Each app has many other models to which Parent and Child, 
respectively, are closely tied - which is why they are in those apps.


If so, what is the best practices way of doing so, and

how does one avoid or minimize circular imports?


In the other apps you don't need to import Parent and Child for FK and 
such. That completely avoids circular imports. If your Parent and Child 
classes are defined in the parentchild app then you specify your FK like 
this ...


class ThisThing(models.Model):
parent = models.ForeignKey("parentchild.Parent")
...

class OtherThing(models.Model):
child = models.ForeignKey("parentchild.Child")
...

For example, if Child.models.py imports Parent in order to facilitate 
the inheritance, what do you do if another model in Parent.models.py 
has a fk to another model in Child.models.py?


You can also use quotes to specify the model class here. Just omit the 
app name if they are in the same app.


Mike


--
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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/01251136-3cfb-4069-862c-78e118475958%40googlegroups.com 
.

For more options, visit https://groups.google.com/d/optout.


--
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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/e7418590-1a87-518d-478a-1718463a2ce0%40dewhirst.com.au.
For more options, visit https://groups.google.com/d/optout.


Model Inheritance across apps

2016-09-29 Thread Malik Rumi
Assume two models, class Parent(models.Model): and Child(Parent):

Assume they are both in the same Project

Can Child be in a different app than Parent? In most cases the answer seems 
to be yes.

Each app has many other models to which Parent and Child, respectively, are 
closely tied - which is why they are in those apps.

If so, what is the best practices way of doing so, and

how does one avoid or minimize circular imports?

For example, if Child.models.py imports Parent in order to facilitate the 
inheritance, what do you do if another model in Parent.models.py has a fk 
to another model in Child.models.py?

-- 
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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/01251136-3cfb-4069-862c-78e118475958%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Queries regarding Custom Managers with model inheritance.

2016-06-09 Thread Dheerendra Rathor
I was going 
through 
https://docs.djangoproject.com/en/1.9/topics/db/managers/#custom-managers-and-model-inheritance
 
regarding custom managers and I decided to do some tests. Here are my 
models:

from django.db import models


class CustomManager(models.Manager):

use_for_related_fields = True


class ExtraManager(models.Manager):
use_for_related_fields = True


class AnotherManager(models.Manager):
use_for_related_fields = True


class A(models.Model):

objects = CustomManager()

all_objects = AnotherManager()

class Meta:
abstract = True


class B(A):
pass


class C(A):
objects = ExtraManager()


class D(C):
pass


class E(A):
all_objects = AnotherManager()
objects = ExtraManager()


class F(E):
pass


Here are the results of few code executions:

In [1]: from app.models import *

In [2]: F.objects
Out[2]: 

In [3]: D.objects
Out[3]: 

In [4]: D._default_manager
Out[4]: 

In [5]: F._de
F._default_manager  F._deferred 

In [5]: F._default_manager
Out[5]: 

In [6]: F.all_objects
Out[6]: 



Here I have few queries:
- How come AnotherManager is default Manage for D? It is neither default 
manager for C and neither it is first Manager in A.
 
- Why D.objects is ExtraManager (from C objects) but F.objects is default 
Django Manager

Someone please help to understand theses. 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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/45df67aa-3d06-4ef5-a736-42c5ff773228%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Model inheritance with constraints

2016-06-02 Thread James Schneider
On Wed, Jun 1, 2016 at 12:45 PM, Arnab Banerji  wrote:

> Nevermind my last comment on this thread, when I refactored my existing
> model into an abstract base class with overrides, and then ran
> "makemigrations", Django said "no changed detected", so it is merely
> treated as a code refactor and not a database related change.
>
>
Yep, that was the whole intention of using the abstract classes. Glad it
worked out for you.

-James

-- 
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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2Be%2BciWK_SrqZCtjB7BxCqByrEcMWWoLx7oE3oOZHwtiQdN_VQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Model inheritance with constraints

2016-06-01 Thread Arnab Banerji
Nevermind my last comment on this thread, when I refactored my existing 
model into an abstract base class with overrides, and then ran 
"makemigrations", Django said "no changed detected", so it is merely 
treated as a code refactor and not a database related change.

Thanks
AB

-- 
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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/d08ff0d6-63c2-4916-bb0e-6c81dbc7faec%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Model inheritance with constraints

2016-06-01 Thread Arnab Banerji
Hi Akhil - my issue was how to avoid the new OneToOne relationships, which 
James addressed on this post.

Hi James - thanks a bunch for your help, much appreciated. While I like the 
WYSIWYG nature of this solution, I am not sure if the creation of the 
abstract base class will cause the data already existing in MyFunModel 
table to be modified in any way. 

Cheers
AB

-- 
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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/eaf73ae9-6b9f-4518-b751-e9c2f776caa1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Model inheritance with constraints

2016-05-29 Thread James Schneider
>
>
> What I have
> =
>
> class MyFunModel(models.Model):
> my_foo_field = 
>
> What I am attempting to add
> =
>
> class MyAnotherFunModel(MyFunModel):
> my_another_foo_field = 
>
> Such that the migration gives me *only* _myanotherfunmodel table with
> fields "my_foo_field" and "my_another_foo_field", *without* touching any
> data in the _myfunmodel table.
>
> None of the options in
> https://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance
> seem to address this case, or maybe I am missing something?
>

If I understand your requirements, then yes, you are missing something. I
believe you are being affected by a consequence of multi-table inheritance
in Django:

https://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance

The first paragraph talks about an 'automatic' OneToOne relationship
between the parent and child tables being created (which is annoying IMO).
This is likely what you are seeing in your migrations. I don't think that
MyFunModel is being directly affected (at least in the DB), but you are
likely seeing an extra table being built for this new relationship with
MyAnotherFunModel.

To get around this, you would need to redefine your common fields into an
abstract model, and then your two concrete models would inherit from your
new abstract model:

https://docs.djangoproject.com/en/dev/topics/db/models/#abstract-base-classes

class FunAbstractModel(models.Model):
my_foo_field = 

class Meta:
abstract = True

class MyFunModel(FunAbstractModel):
pass

class MyAnotherFunModel(FunAbstractModel):
my_another_foo_field = 

Both of your concrete models (MyFunModel and MyAnotherFunModel) will
contain a 'my_foo_field' field, but MyAnotherFunModel will also contain
'my_another_foo_field'. There will also be no automatic relationship built
between the two models since they no longer inherit from each other (both
inherit from FunAbstractModel, which is abstract so it doesn't directly
affect your database).

You should be able to make this change transparently and get the results
you want if you replicate all of the appropriate fields in FunAbstractModel
that are currently used by MyFunModel.

I personally never use MTI and always use abstract models to handle these
cases. If I need a OneToOne, I enter it manually in the code so that I
don't have to remember it is there down the road, since I usually only look
at the model definition and not check through the inheritance tree for
magic relationships. I haven't personally found a use-case where I was fine
with an implicit relationship rather than an explicit one.

-James

-- 
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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2Be%2BciWLzbnzbGYCUBjYhNncr1kg7%3DomRztxdQ61bxkyGqQCFQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Model inheritance with constraints

2016-05-28 Thread Akhil Lawrence
Its already addressed.

You can simply run ./manage.py makemigrations and ./manage.py migrate

it will create migrations only for MyAnotherFunModel





On Thursday, 26 May 2016 01:02:08 UTC+5:30, Arnab Banerji wrote:
>
> Hi all,
>
> I currently have a set of models associated with my Django app, with the 
> database already containing data with respect to these tables (models). 
>
> What I have
> =
>
> class MyFunModel(models.Model):
> my_foo_field = 
>
> What I am attempting to add
> =
>
> class MyAnotherFunModel(MyFunModel):
> my_another_foo_field = 
>
> Such that the migration gives me *only* _myanotherfunmodel table with 
> fields "my_foo_field" and "my_another_foo_field", *without* touching any 
> data in the _myfunmodel table. 
>
> None of the options in 
> https://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance 
> seem to address this case, or maybe I am missing something?
>
> Thanks,
> AB
>

-- 
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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/fbc77543-ee22-4b61-a295-b5f1870b1648%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Model inheritance with constraints

2016-05-25 Thread Arnab Banerji
Hi all,

I currently have a set of models associated with my Django app, with the 
database already containing data with respect to these tables (models). 

What I have
=

class MyFunModel(models.Model):
my_foo_field = 

What I am attempting to add
=

class MyAnotherFunModel(MyFunModel):
my_another_foo_field = 

Such that the migration gives me *only* _myanotherfunmodel table with 
fields "my_foo_field" and "my_another_foo_field", *without* touching any 
data in the _myfunmodel table. 

None of the options 
in https://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance 
seem to address this case, or maybe I am missing something?

Thanks,
AB

-- 
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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/4f897668-3400-4d28-9c67-5d303ddd27e8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: proxy model inheritance generates a migration file in a third party app

2016-01-29 Thread Iliana Toneva
Hi Markus,


Thank you very much, that solved the issue.

Many thanks,
Iliana



On Thursday, 28 January 2016 17:31:36 UTC-7, Markus Holtermann wrote:
>
> Hello Iliana,
>
> this is due to the definition of app_label = 'actstream' on your proxy 
> model. This tells Django that this model should belong to another app. 
> Hence the migrations involving that model are added to the actstream app's 
> migrations.
>
> /Markus
>
>
> On Friday, January 29, 2016 at 10:14:24 AM UTC+11, Iliana Toneva wrote:
>>
>>  
>> Hello,
>>
>> I am using a third party app actstream 
>>  (
>> https://github.com/justquick/django-activity-stream) and am creating a 
>> proxy for one of the original actstream models :
>>
>> # myapp/models.py
>> from actstream.models import Action
>>
>> # Subclass Action model and apply my own manager 
>> class MyAction(Action):
>> objects = MyActionManager()
>>
>> class Meta:
>> proxy = True
>> app_label = 'actstream'
>>
>>
>> The issue that I am having is that when I run './manage.py makemigrations', 
>> that creates a migration file 0002_myaction.py and adds it to the third 
>> party app migrations (instead of adding it to myapp/migrations):
>>
>>
>> *Migrations for 'actstream':*
>>
>>   *0002_myaction.py*:
>>
>> - Create proxy model MyAction
>>
>>
>> # actstream/migrations/0002_myaction.py
>>
>> # -*- coding: utf-8 -*-
>> from __future__ import unicode_literals
>>
>> from django.db import migrations, models
>>
>>
>> class Migration(migrations.Migration):
>>
>> dependencies = [
>> ('actstream', '0001_initial'),
>> ]
>>
>> operations = [
>> migrations.CreateModel(
>> name='MyAction',
>> fields=[
>> ],
>> options={
>> 'proxy': True,
>> },
>> bases=('actstream.action',),
>> ),
>> ]
>>
>> Is there a way to prevent this behavior and force './manage.py 
>> makemigrations' to create a migration file in myapp/migrations/ instead? 
>>
>> Many thanks,
>> Iliana
>>
>>

-- 
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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/1c1ed33b-0838-4905-8d92-8007eca2ae18%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: proxy model inheritance generates a migration file in a third party app

2016-01-28 Thread Markus Holtermann
Hello Iliana,

this is due to the definition of app_label = 'actstream' on your proxy 
model. This tells Django that this model should belong to another app. 
Hence the migrations involving that model are added to the actstream app's 
migrations.

/Markus


On Friday, January 29, 2016 at 10:14:24 AM UTC+11, Iliana Toneva wrote:
>
>  
> Hello,
>
> I am using a third party app actstream 
>  (
> https://github.com/justquick/django-activity-stream) and am creating a 
> proxy for one of the original actstream models :
>
> # myapp/models.py
> from actstream.models import Action
>
> # Subclass Action model and apply my own manager 
> class MyAction(Action):
> objects = MyActionManager()
>
> class Meta:
> proxy = True
> app_label = 'actstream'
>
>
> The issue that I am having is that when I run './manage.py makemigrations', 
> that creates a migration file 0002_myaction.py and adds it to the third party 
> app migrations (instead of adding it to myapp/migrations):
>
>
> *Migrations for 'actstream':*
>
>   *0002_myaction.py*:
>
> - Create proxy model MyAction
>
>
> # actstream/migrations/0002_myaction.py
>
> # -*- coding: utf-8 -*-
> from __future__ import unicode_literals
>
> from django.db import migrations, models
>
>
> class Migration(migrations.Migration):
>
> dependencies = [
> ('actstream', '0001_initial'),
> ]
>
> operations = [
> migrations.CreateModel(
> name='MyAction',
> fields=[
> ],
> options={
> 'proxy': True,
> },
> bases=('actstream.action',),
> ),
> ]
>
> Is there a way to prevent this behavior and force './manage.py 
> makemigrations' to create a migration file in myapp/migrations/ instead? 
>
> Many thanks,
> Iliana
>
>

-- 
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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/4c72ac4c-34fb-433e-8d62-82c83855a8b8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


proxy model inheritance generates a migration file in a third party app

2016-01-28 Thread Iliana Toneva
 
Hello,

I am using a third party app actstream 
 
(https://github.com/justquick/django-activity-stream) and 
am creating a proxy for one of the original actstream models :

# myapp/models.py
from actstream.models import Action

# Subclass Action model and apply my own manager 
class MyAction(Action):
objects = MyActionManager()

class Meta:
proxy = True
app_label = 'actstream'


The issue that I am having is that when I run './manage.py makemigrations', 
that creates a migration file 0002_myaction.py and adds it to the third party 
app migrations (instead of adding it to myapp/migrations):


*Migrations for 'actstream':*

  *0002_myaction.py*:

- Create proxy model MyAction


# actstream/migrations/0002_myaction.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('actstream', '0001_initial'),
]

operations = [
migrations.CreateModel(
name='MyAction',
fields=[
],
options={
'proxy': True,
},
bases=('actstream.action',),
),
]

Is there a way to prevent this behavior and force './manage.py 
makemigrations' to create a migration file in myapp/migrations/ instead? 

Many thanks,
Iliana

-- 
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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/e9d0d1d0-9bf9-435c-b569-32c7a1bb2edb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django model inheritance: create sub-instance of existing instance (downcast)?

2015-05-18 Thread guettli
Thank you Simon. I did not know save_base(raw=True) before.

Am Mittwoch, 13. Mai 2015 16:43:36 UTC+2 schrieb Simon Charette:
>
> Hi Guettli,
>
> This isn't part of the public API but you could rely on how Django loads 
> fixture internally 
> <https://github.com/django/django/blob/3c8fe5dddf34533a419d2deed5208a28de32cb4a/django/core/serializers/base.py#L169-L180>
> .
>
> parent = Restaurant.objects.get(name__iexact="Bob's Place").parent
> bar = Bar(parent=parent, happy_hour=True)
> bar.save_base(raw=True)
>
> Keep in mind that this could break with any new version of Django.
>
> Simon
>
> Le mercredi 13 mai 2015 05:25:50 UTC-4, guettli a écrit :
>>
>> Thank you for this link. The InheritanceManager is good to know about. 
>> But it does not help creating the child_instance from a base instance. At 
>> least the docs don't tell about it. Or I was blind.
>>
>> Am Mittwoch, 13. Mai 2015 05:41:44 UTC+2 schrieb somecallitblues:
>>>
>>> Have you had a look at 
>>> http://django-model-utils.readthedocs.org/en/latest/managers.html#inheritancemanager?
>>>  
>>> I'm not sure if it will help but it's kind of related to what you've posted.
>>>
>>> On 12 May 2015 at 23:10, guettli <h...@tbz-pariv.de> wrote:
>>>
>>>> Hi,
>>>>
>>>> this ticket is seven years old
>>>>
>>>> https://code.djangoproject.com/ticket/7623
>>>>
>>>> {{{
>>>>
>>>> As it exists now, multi-table inheritance does not allow for the 
>>>> creation of a child model instance that inherits from an existing parent 
>>>> model instance. For example:
>>>>  
>>>> Parent Class-
>>>>  
>>>> class Place(models.Model):
>>>> name = models.CharField(max_length=50)
>>>> address = models.TextField(max_length=150)
>>>>
>>>> Child Classes-
>>>>  
>>>> class Restaurant(Place):
>>>> place = models.OneToOneField(Place, parent_link=True)
>>>> cuisine = models.CharField(max_length=75)
>>>> rating = models.IntegerField()
>>>>
>>>> class Bar(Place):
>>>> parent = models.OneToOneField(Place, parent_link=True)
>>>> happy_hour = models.BooleanField()
>>>> beers_on_tap = models.ManyToManyField("Beers", null=True, blank=True)
>>>>
>>>> Sample Use-case-
>>>>  
>>>> When the system is first deployed, a restaurant instance is created. 
>>>> Later, the restaurant adds a bar to increase revenue, and we now want to 
>>>> create a Bar model instance for the parent Place for the restaurant. I 
>>>> would propose the following interface for doing so:
>>>>  
>>>> parentPlace = Restaurant.objects.get(name__iexact="Bob's Place").parent
>>>> barInstance = Bar(parent=parentPlace, happy_hour=True)
>>>>
>>>> However, if you attempt to create an instance in this manner now, you 
>>>> receive a DatabaseIntegrityError, saying that a Place object with that id 
>>>> already exists.
>>>>
>>>> }}}
>>>>
>>>> How to get this solved?
>>>>
>>>> There are work arounds:
>>>>
>>>>
>>>> http://stackoverflow.com/questions/4064808/django-model-inheritance-create-sub-instance-of-existing-instance-downcast
>>>>
>>>> {{{
>>>> extended_user = ExtendedUser(user_ptr_id=auth_user.pk)
>>>> extended_user.__dict__.update(auth_user.__dict__)
>>>> extended_user.save()
>>>> }}}
>>>>
>>>> Or is there a better solution in current django versions?
>>>>
>>>>
>>>>
>>>>
>>>>
>>>>
>>>>  
>>>>
>>>> -- 
>>>> 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...@googlegroups.com.
>>>> To post to this group, send email to django...@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/d4273754-670e-4697-b0b4-9626c42a5aaf%40googlegroups.com
>>>>  
>>>> <https://groups.google.com/d/msgid/django-users/d4273754-670e-4697-b0b4-9626c42a5aaf%40googlegroups.com?utm_medium=email_source=footer>
>>>> .
>>>> For more options, visit https://groups.google.com/d/optout.
>>>>
>>>
>>>

-- 
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/4a1b1bce-6f5d-4a04-ba40-66b27cb9caef%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django model inheritance: create sub-instance of existing instance (downcast)?

2015-05-13 Thread Simon Charette
Hi Guettli,

This isn't part of the public API but you could rely on how Django loads 
fixture internally 
<https://github.com/django/django/blob/3c8fe5dddf34533a419d2deed5208a28de32cb4a/django/core/serializers/base.py#L169-L180>
.

parent = Restaurant.objects.get(name__iexact="Bob's Place").parent
bar = Bar(parent=parent, happy_hour=True)
bar.save_base(raw=True)

Keep in mind that this could break with any new version of Django.

Simon

Le mercredi 13 mai 2015 05:25:50 UTC-4, guettli a écrit :
>
> Thank you for this link. The InheritanceManager is good to know about. But 
> it does not help creating the child_instance from a base instance. At least 
> the docs don't tell about it. Or I was blind.
>
> Am Mittwoch, 13. Mai 2015 05:41:44 UTC+2 schrieb somecallitblues:
>>
>> Have you had a look at 
>> http://django-model-utils.readthedocs.org/en/latest/managers.html#inheritancemanager?
>>  
>> I'm not sure if it will help but it's kind of related to what you've posted.
>>
>> On 12 May 2015 at 23:10, guettli <h...@tbz-pariv.de> wrote:
>>
>>> Hi,
>>>
>>> this ticket is seven years old
>>>
>>> https://code.djangoproject.com/ticket/7623
>>>
>>> {{{
>>>
>>> As it exists now, multi-table inheritance does not allow for the 
>>> creation of a child model instance that inherits from an existing parent 
>>> model instance. For example:
>>>  
>>> Parent Class-
>>>  
>>> class Place(models.Model):
>>> name = models.CharField(max_length=50)
>>> address = models.TextField(max_length=150)
>>>
>>> Child Classes-
>>>  
>>> class Restaurant(Place):
>>> place = models.OneToOneField(Place, parent_link=True)
>>> cuisine = models.CharField(max_length=75)
>>> rating = models.IntegerField()
>>>
>>> class Bar(Place):
>>> parent = models.OneToOneField(Place, parent_link=True)
>>> happy_hour = models.BooleanField()
>>> beers_on_tap = models.ManyToManyField("Beers", null=True, blank=True)
>>>
>>> Sample Use-case-
>>>  
>>> When the system is first deployed, a restaurant instance is created. 
>>> Later, the restaurant adds a bar to increase revenue, and we now want to 
>>> create a Bar model instance for the parent Place for the restaurant. I 
>>> would propose the following interface for doing so:
>>>  
>>> parentPlace = Restaurant.objects.get(name__iexact="Bob's Place").parent
>>> barInstance = Bar(parent=parentPlace, happy_hour=True)
>>>
>>> However, if you attempt to create an instance in this manner now, you 
>>> receive a DatabaseIntegrityError, saying that a Place object with that id 
>>> already exists.
>>>
>>> }}}
>>>
>>> How to get this solved?
>>>
>>> There are work arounds:
>>>
>>>
>>> http://stackoverflow.com/questions/4064808/django-model-inheritance-create-sub-instance-of-existing-instance-downcast
>>>
>>> {{{
>>> extended_user = ExtendedUser(user_ptr_id=auth_user.pk)
>>> extended_user.__dict__.update(auth_user.__dict__)
>>> extended_user.save()
>>> }}}
>>>
>>> Or is there a better solution in current django versions?
>>>
>>>
>>>
>>>
>>>
>>>
>>>  
>>>
>>> -- 
>>> 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...@googlegroups.com.
>>> To post to this group, send email to django...@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/d4273754-670e-4697-b0b4-9626c42a5aaf%40googlegroups.com
>>>  
>>> <https://groups.google.com/d/msgid/django-users/d4273754-670e-4697-b0b4-9626c42a5aaf%40googlegroups.com?utm_medium=email_source=footer>
>>> .
>>> For more options, visit https://groups.google.com/d/optout.
>>>
>>
>>

-- 
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/c86d6f7e-2c31-4eef-a4db-2b0128241d8c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django model inheritance: create sub-instance of existing instance (downcast)?

2015-05-13 Thread guettli
Thank you for this link. The InheritanceManager is good to know about. But 
it does not help creating the child_instance from a base instance. At least 
the docs don't tell about it. Or I was blind.

Am Mittwoch, 13. Mai 2015 05:41:44 UTC+2 schrieb somecallitblues:
>
> Have you had a look at 
> http://django-model-utils.readthedocs.org/en/latest/managers.html#inheritancemanager?
>  
> I'm not sure if it will help but it's kind of related to what you've posted.
>
> On 12 May 2015 at 23:10, guettli <h...@tbz-pariv.de > wrote:
>
>> Hi,
>>
>> this ticket is seven years old
>>
>> https://code.djangoproject.com/ticket/7623
>>
>> {{{
>>
>> As it exists now, multi-table inheritance does not allow for the creation 
>> of a child model instance that inherits from an existing parent model 
>> instance. For example:
>>  
>> Parent Class-
>>  
>> class Place(models.Model):
>> name = models.CharField(max_length=50)
>> address = models.TextField(max_length=150)
>>
>> Child Classes-
>>  
>> class Restaurant(Place):
>> place = models.OneToOneField(Place, parent_link=True)
>> cuisine = models.CharField(max_length=75)
>> rating = models.IntegerField()
>>
>> class Bar(Place):
>> parent = models.OneToOneField(Place, parent_link=True)
>> happy_hour = models.BooleanField()
>> beers_on_tap = models.ManyToManyField("Beers", null=True, blank=True)
>>
>> Sample Use-case-
>>  
>> When the system is first deployed, a restaurant instance is created. 
>> Later, the restaurant adds a bar to increase revenue, and we now want to 
>> create a Bar model instance for the parent Place for the restaurant. I 
>> would propose the following interface for doing so:
>>  
>> parentPlace = Restaurant.objects.get(name__iexact="Bob's Place").parent
>> barInstance = Bar(parent=parentPlace, happy_hour=True)
>>
>> However, if you attempt to create an instance in this manner now, you 
>> receive a DatabaseIntegrityError, saying that a Place object with that id 
>> already exists.
>>
>> }}}
>>
>> How to get this solved?
>>
>> There are work arounds:
>>
>>
>> http://stackoverflow.com/questions/4064808/django-model-inheritance-create-sub-instance-of-existing-instance-downcast
>>
>> {{{
>> extended_user = ExtendedUser(user_ptr_id=auth_user.pk)
>> extended_user.__dict__.update(auth_user.__dict__)
>> extended_user.save()
>> }}}
>>
>> Or is there a better solution in current django versions?
>>
>>
>>
>>
>>
>>
>>  
>>
>> -- 
>> 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...@googlegroups.com .
>> To post to this group, send email to django...@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/d4273754-670e-4697-b0b4-9626c42a5aaf%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/d4273754-670e-4697-b0b4-9626c42a5aaf%40googlegroups.com?utm_medium=email_source=footer>
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>

-- 
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/274e9ef0-afb5-4b73-80ce-19440a78ecfb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django model inheritance: create sub-instance of existing instance (downcast)?

2015-05-12 Thread Mario Gudelj
Have you had a look at
http://django-model-utils.readthedocs.org/en/latest/managers.html#inheritancemanager?
I'm not sure if it will help but it's kind of related to what you've posted.

On 12 May 2015 at 23:10, guettli <h...@tbz-pariv.de> wrote:

> Hi,
>
> this ticket is seven years old
>
> https://code.djangoproject.com/ticket/7623
>
> {{{
>
> As it exists now, multi-table inheritance does not allow for the creation
> of a child model instance that inherits from an existing parent model
> instance. For example:
>
> Parent Class-
>
> class Place(models.Model):
> name = models.CharField(max_length=50)
> address = models.TextField(max_length=150)
>
> Child Classes-
>
> class Restaurant(Place):
> place = models.OneToOneField(Place, parent_link=True)
> cuisine = models.CharField(max_length=75)
> rating = models.IntegerField()
>
> class Bar(Place):
> parent = models.OneToOneField(Place, parent_link=True)
> happy_hour = models.BooleanField()
> beers_on_tap = models.ManyToManyField("Beers", null=True, blank=True)
>
> Sample Use-case-
>
> When the system is first deployed, a restaurant instance is created.
> Later, the restaurant adds a bar to increase revenue, and we now want to
> create a Bar model instance for the parent Place for the restaurant. I
> would propose the following interface for doing so:
>
> parentPlace = Restaurant.objects.get(name__iexact="Bob's Place").parent
> barInstance = Bar(parent=parentPlace, happy_hour=True)
>
> However, if you attempt to create an instance in this manner now, you
> receive a DatabaseIntegrityError, saying that a Place object with that id
> already exists.
>
> }}}
>
> How to get this solved?
>
> There are work arounds:
>
>
> http://stackoverflow.com/questions/4064808/django-model-inheritance-create-sub-instance-of-existing-instance-downcast
>
> {{{
> extended_user = ExtendedUser(user_ptr_id=auth_user.pk)
> extended_user.__dict__.update(auth_user.__dict__)
> extended_user.save()
> }}}
>
> Or is there a better solution in current django versions?
>
>
>
>
>
>
>
>
> --
> 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/d4273754-670e-4697-b0b4-9626c42a5aaf%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/d4273754-670e-4697-b0b4-9626c42a5aaf%40googlegroups.com?utm_medium=email_source=footer>
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 
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/CAHqTbjnRG5iYVHhabR_6YytCRgRpxyYayj-aOSuFFrom5wi%3Duw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Django model inheritance: create sub-instance of existing instance (downcast)?

2015-05-12 Thread guettli
Hi,

this ticket is seven years old

https://code.djangoproject.com/ticket/7623

{{{

As it exists now, multi-table inheritance does not allow for the creation 
of a child model instance that inherits from an existing parent model 
instance. For example:
 
Parent Class-
 
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.TextField(max_length=150)

Child Classes-
 
class Restaurant(Place):
place = models.OneToOneField(Place, parent_link=True)
cuisine = models.CharField(max_length=75)
rating = models.IntegerField()

class Bar(Place):
parent = models.OneToOneField(Place, parent_link=True)
happy_hour = models.BooleanField()
beers_on_tap = models.ManyToManyField("Beers", null=True, blank=True)

Sample Use-case-
 
When the system is first deployed, a restaurant instance is created. Later, 
the restaurant adds a bar to increase revenue, and we now want to create a 
Bar model instance for the parent Place for the restaurant. I would propose 
the following interface for doing so:
 
parentPlace = Restaurant.objects.get(name__iexact="Bob's Place").parent
barInstance = Bar(parent=parentPlace, happy_hour=True)

However, if you attempt to create an instance in this manner now, you 
receive a DatabaseIntegrityError, saying that a Place object with that id 
already exists.

}}}

How to get this solved?

There are work arounds:

http://stackoverflow.com/questions/4064808/django-model-inheritance-create-sub-instance-of-existing-instance-downcast

{{{
extended_user = ExtendedUser(user_ptr_id=auth_user.pk)
extended_user.__dict__.update(auth_user.__dict__)
extended_user.save()
}}}

Or is there a better solution in current django versions?






 

-- 
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/d4273754-670e-4697-b0b4-9626c42a5aaf%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: OneToOne field versus model inheritance

2015-01-22 Thread Collin Anderson
Hi,

Django doesn't really provide a way to create a subclass from an already 
existing object in the admin. It's actually pretty hard to do even in the 
code. So for that reason I'd recommend the non subclass with the 
OneToOneField.

Actually, if I were doing it, this is what I would do:

class User(AbstractBaseUser):
is_client = models.BooleanField(default=False)
is_member = models.BooleanField(default=False)
description = models.CharField(verbose_name=_('first name'), max_length=
255, blank=True)
# include both client and member fields here and have them be blank=True

Collin

On Tuesday, January 20, 2015 at 7:52:38 AM UTC-5, Paul Royik wrote:
>
> I have three models: Person, Client, Member
> Person is a base model, Client and Member are profiles for Person.
>
> class Person(AbstractBaseUser, PermissionsMixin):
> email = models.EmailField(
> verbose_name=_('email address'),
> max_length=255,
> unique=True,
> )
>
>
> class Client(User): #or maybe models.Model and explicit OneToField 
> first_name = models.CharField(verbose_name=_('first name'), 
> max_length=30)
> last_name = models.CharField(verbose_name=_('last name'), 
> max_length=30)
>
> class Member(User): #or maybe models.Model and explicit OneToField 
> description = models.CharField(verbose_name=_('first name'), 
> max_length=255)
># other stuff
>
>
> So, what I want?
> 1. In admin, when we add client or member, I want to fill field email 
> (fields from base class) as if it was in derived class. For example, in 
> admin list_display = ('email', 'first_name'). Not select boxes for user.
> 2. Person class can be instantiated separately and the "attached" to the 
> created profiel. Like person=Person(email="te...@gmail.com "), 
> client = Client(person=person,first_name="test"...). Especially, this 
> should work in forms. When user (person) is authenticated I want to give 
> ability to fill in profile (client) form and attach person to this form.
> 3. One person can have both accounts. If I delete client/member, 
> corresponding person should not be deleted.
>
> 3rd option actually is not necessary, but it is useful for me to know how 
> to do it.
>
> So, option 1 is perfectly solved by inheritance, Person is User, but this 
> approach fails when option 2 is implemented. Since Person and Client is 
> considered as one whole, I can't attach user, duplicate key error.
> Option 2 is resolved by extending models.Model and appending 
> person=models.OnetoOneField(Person,primary_key=True). However, admin is 
> broken (1st option), because Client don't have fields like email.
>
>
> So, what approach to take in order to solve above issues?
> Are there simple ways?
> If there are no simple ways, is there advanced way, like overriding 
> metaclass, object descriptors or writing custom OneToOne field?
>
> Any suggestions are welcomed.
>
> Thank you. 
>

-- 
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/d8ca1b3c-59fe-434a-bbe7-e916d0312e9c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


OneToOne field versus model inheritance

2015-01-20 Thread Paul Royik
I have three models: Person, Client, Member
Person is a base model, Client and Member are profiles for Person.

class Person(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name=_('email address'),
max_length=255,
unique=True,
)


class Client(User): #or maybe models.Model and explicit OneToField 
first_name = models.CharField(verbose_name=_('first name'), 
max_length=30)
last_name = models.CharField(verbose_name=_('last name'), max_length=30)

class Member(User): #or maybe models.Model and explicit OneToField 
description = models.CharField(verbose_name=_('first name'), 
max_length=255)
   # other stuff


So, what I want?
1. In admin, when we add client or member, I want to fill field email 
(fields from base class) as if it was in derived class. For example, in 
admin list_display = ('email', 'first_name'). Not select boxes for user.
2. Person class can be instantiated separately and the "attached" to the 
created profiel. Like person=Person(email="t...@gmail.com"), client = 
Client(person=person,first_name="test"...). Especially, this should work in 
forms. When user (person) is authenticated I want to give ability to fill 
in profile (client) form and attach person to this form.
3. One person can have both accounts. If I delete client/member, 
corresponding person should not be deleted.

3rd option actually is not necessary, but it is useful for me to know how 
to do it.

So, option 1 is perfectly solved by inheritance, Person is User, but this 
approach fails when option 2 is implemented. Since Person and Client is 
considered as one whole, I can't attach user, duplicate key error.
Option 2 is resolved by extending models.Model and appending 
person=models.OnetoOneField(Person,primary_key=True). However, admin is 
broken (1st option), because Client don't have fields like email.


So, what approach to take in order to solve above issues?
Are there simple ways?
If there are no simple ways, is there advanced way, like overriding 
metaclass, object descriptors or writing custom OneToOne field?

Any suggestions are welcomed.

Thank you. 

-- 
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/280bb9b1-f667-423d-81e3-4ea6e0c84c59%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Possible Model Inheritance Issue? Error: [Model_Name] instance needs to have a primary key value before a many-to-many relationship can be used

2014-05-11 Thread João Pedro Melo
I know this is a VERY VERY old thread but oh my god I love you, I was 
having the same problem for the same reason and would have never imaged 
that was why (though it makes sense). Took me a long time to finally find 
this thread.

On Thursday, January 22, 2009 1:38:57 AM UTC-2, Keyton Weissinger wrote:
>
> OK. I figured it out and it was VERY STRANGE. Maybe some one reading 
> this can tell me WWWHHHYYY my solution works. For now, it's voodoo to 
> me... 
>
> Turns out that some of my code (in the view where I was having 
> trouble) called some code that looked sort of like this: 
>
> field_list = model._meta.fields 
> field_list.extend(model._meta.many_to_many) 
> for field in field_list: 
> related_model_name = None 
> related_model_app_name = None 
> if (not field.name[-4:] == '_ptr') and (not field.__class__ == 
> AutoField): 
>
> if issubclass(field.__class__, related.RelatedField): 
> if not field.__class__ == related.ForeignKey: 
> related_model_app_name = field.rel.to.__module__.split 
> ('.')[0] 
> # We'll ignore all django-specific models (such as 
> User, etc). 
> if not related_model_app_name == 'django': 
> related_model_name = field.rel.to.__name__ 
> full_related_model_name = '.'.join 
> ([field.rel.to.__module__, related_model_name]) 
> relation_tuple_list.append((full_model_name 
> +'%relation'+field.name+'%' + full_related_model_name, \ 
> 'Mapping: ' + 
> model.__name__ + '-' + \ 
> related_model_name)) 
> else: 
> continue 
>
> It is just pulling together a list of relationships between two 
> models. I'm not using these models to actually DO anything. Just what 
> you see. 
>
> I could go to the command line and do the following: 
> >>> from batchimport.forms import ImportOptionsForm 
> >>> from sbase.models import Student 
> >>> mydict = {'city': u'Columbus', 'first_name': u'Jimmy', 'last_name': 
> u'Jones', 'zip': 43215.0, 'title': u'Mr.', 'dob': '1956-12-29', 
> 'phone_primary': u'614-468-5940', 'state': u'OH', 'address': u'142, Quilly 
> Lane', 'type': u'Student', 'email': u'miles...@spambob.com '} 
>
> >>> mystudent = Student(**mydict) 
>
> The import of ImportOptionsForms, it turns out, called the above code. 
>
> OK. The above series of commands would fail every time with the 
> following error. 
> 'Student' instance needs to have a primary key value before a many-to- 
> many relationship can be used. 
>
> I was close. I could repeat my strange in-app problem on the command 
> line. Yea. 
>
> So after a LONG time of messing with it, it turns out that django 
> didn't like how I was handling the many-to-many fields 
> (model._meta.many_to_many). 
>
> But I was able to fix my problem by just doing this: 
>
> for field_list in [model._meta.fields, model._meta.many_to_many]: 
> for field in field_list: 
> related_model_name = None 
> related_model_app_name = None 
> if (not field.name[-4:] == '_ptr') and (not 
> field.__class__ == AutoField): 
>
> if issubclass(field.__class__, related.RelatedField): 
> if not field.__class__ == related.ForeignKey: 
> related_model_app_name = 
> field.rel.to.__module__.split('.')[0] 
> # We'll ignore all django-specific models 
> (such as User, etc). 
> if not related_model_app_name == 'django': 
> related_model_name = field.rel.to.__name__ 
> full_related_model_name = '.'.join 
> ([field.rel.to.__module__, related_model_name]) 
> relation_tuple_list.append((full_model_name 
> +'%relation'+field.name+'%' + full_related_model_name, \ 
> 'Mapping: ' + 
> model.__name__ + '-' + \ 
>   
> related_model_name)) 
> else: 
> continue 
>
> YEAH! That's all I changed. Instead of extending my list of fields 
> with the many_to_many fields, I just iterated over one (to get the 
> ForeignKey relationships etc, and then I subsequently iterated over my 
> many-to-many fields. 
>
> Why (the HELL) does the first version trigger this error: 
> 'Student' instance needs to have a primary key value before a many-to- 
> many relationship can be used. 
>
> But the second version doesn't? 
>
> If I'm an idiot, PLEASE tell me how so, because I'd really like to 
> avoid this kind of quagmire if I can 
>
> Thank you VERY MUCH Martin and Malcolm. I appreciate your respective 
> looks at this problem very much. Your taking time to help with this 
> kind of thorny issue is what makes this community rock and, frankly, 
> inspires me to help out more. 
>
> Keyton 
>
> On Jan 21, 

True Model Inheritance

2014-04-11 Thread Thomas Güttler

I know that there are several model inheritance extensions available:

https://www.djangopackages.com/grids/g/model-inheritance/

But it is hard for me to decide which one to take.

The most common solutions seem to be:

django-model-utils
django-polymorphic

My use case is simple:

This query should return instances of child classes:

for obj in BaseClass.objects.filter(...)
...

Which solution do you use, and why?

  Thomas

--
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/5347E419.3050503%40tbz-pariv.de.
For more options, visit https://groups.google.com/d/optout.


Re: db performance with model inheritance vs. alternatives

2013-12-04 Thread Matthias Dahl
Hello @all,

just to be clear and honest upfront: I've just posted this question on


http://stackoverflow.com/questions/20373194/db-performance-with-model-inheritance-vs-alternatives

as well. I hope this is okay and doesn't upset anyone.

Thanks again.

So long,
Matthias

-- 
Dipl.-Inf. (FH) Matthias Dahl | Software Engineer | binary-island.eu
 services: custom software [desktop, mobile, web], server administration

-- 
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/529F0837.1040606%40binary-island.eu.
For more options, visit https://groups.google.com/groups/opt_out.


db performance with model inheritance vs. alternatives

2013-12-04 Thread Matthias Dahl
Hello @all,

sorry for the cryptic subject but summarizing what this mail is about,
is kind of hard. :) So please bear with me for a moment...

I am working on an application that is designed to be highly modular and
extendable (by means of plugins). So basically you have models that are
stripped down to a bare minimum of data and behavior (the common set)
while the rest can come in via plugins.

For example: An admin creates instances of a model through the admin.
Some require just the basics but others do require special behavior and
some extra data, thus he adds plugins to those.

What jumps to mind is model inheritance for the plugins. But since it is
unforeseeable how many plugins an installation will have and how many a
specific model instance will have attached to it or what kind of plugins
(since the plugin system is heterogenous), performance is a great
concern of mine.

Each time a model is utilized for a site's visitor, every plugin needs
to get evaluated.

Thus I want to make sure that I get everything for a model with 1 query
instead of several. This naturally can result in quite a lot of joins,
actually at least O(N) (with N being the number of plugins that the
system has installed for a specific model type). This alone worries me
about the scalability and feasibility of such a system.

So I'd like to ask the community for advice if my concerns are justified
and if this is a sound approach? By the way, after having implemented my
own solution, I came across the InheritanceManager from
django-model-utils which is what is used now for the downcasting part
(if that matters).

Right now I am also thinking about possible alternatives without loosing
the flexibility of the plugin system itself (which is a necessity):

Instead of saving each plugin to its own table, the plugin system could
be designed to utilize just one table with all the common plugin meta
data saved as columns and the rest is being serialized to JSON and saved
as such in another column. Thus, one could very easily get all plugins
for a model and only had to construct the plugin model manually with the
serialized data. This would work just fine with heterogenous and
homogenous plugins. Naturally a plugin (and the overall system) looses
some options when it comes to querying the database for specifics
of a plugin's serialized data. Also there are ACID constraints like not
being able to atomically increment a single field. But those limitations
would be fine and could also be overcome if a plugin required it (by
means of a dedicated data model for example).

Again, I'd kindly ask for advice if this would be a more scalable
approach compared to my initial solution above or if this is something
that just stinks of problems and should be avoided at all costs? ;)

Thanks in advance for any help and hints in advance. It is very much
appreciated...

So long,
Matthias

-- 
Dipl.-Inf. (FH) Matthias Dahl | Software Engineer | binary-island.eu
 services: custom software [desktop, mobile, web], server administration

-- 
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/529EFF22.2070903%40binary-island.eu.
For more options, visit https://groups.google.com/groups/opt_out.


Re: model inheritance

2013-10-02 Thread Roberto López López

Is there maybe a way to set the cmsplugin_news.News.Meta.abstract option
to True? In order to prevent accessing the parent model to fetch the
inherited data.



On 10/02/2013 03:45 PM, Leonardo Giordani wrote:
> Are you sure your DB has been synced after putting the
> ForeignKey(News) in your Department model?
> Can you post somewhere the following models: News, OldNews, Department?
>
> Regards,
>
> Leo
>
> Leonardo Giordani
> Author of The Digital Cat 
> My profile on About.me  - My GitHub
> page  - My Coderwall profile
> 
>
>
> 2013/10/2 Roberto López López  >
>
> Hi,
>
> I am extending a 3rd party model in my application, using
> multi-table inheritance. I can create an instance and modify it,
> but when I try to list the created objects at
> http://localhost:8000/en/admin/news/news/ , I am getting a nice
> exception:
>
> Traceback:
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/core/handlers/base.py"
> in get_response
>   140. response = response.render()
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/response.py"
> in render
>   105. self.content = self.rendered_content
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/response.py"
> in rendered_content
>   82. content = template.render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in render
>   140. return self._render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in _render
>   134. return self.nodelist.render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in render
>   830. bit = self.render_node(node, context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/debug.py"
> in render_node
>   74. return node.render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/loader_tags.py"
> in render
>   124. return compiled_parent._render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in _render
>   134. return self.nodelist.render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in render
>   830. bit = self.render_node(node, context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/debug.py"
> in render_node
>   74. return node.render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/loader_tags.py"
> in render
>   124. return compiled_parent._render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in _render
>   134. return self.nodelist.render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in render
>   830. bit = self.render_node(node, context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/debug.py"
> in render_node
>   74. return node.render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/loader_tags.py"
> in render
>   63. result = block.nodelist.render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in render
>   830. bit = self.render_node(node, context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/debug.py"
> in render_node
>   74. return node.render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/loader_tags.py"
> in 

Re: model inheritance

2013-10-02 Thread Roberto López López

Hi Leonardo, thanks for your answer.

Yes, it has been synced.

The model itself is a little bit bigger, as you can notice from the code
https://dpaste.de/c3Rg I am using as well the News model from
https://github.com/wildfish/cmsplugin_news/blob/master/cmsplugin_news/models.py

Regards,

Roberto





On 10/02/2013 03:45 PM, Leonardo Giordani wrote:
> Are you sure your DB has been synced after putting the
> ForeignKey(News) in your Department model?
> Can you post somewhere the following models: News, OldNews, Department?
>
> Regards,
>
> Leo
>
> Leonardo Giordani
> Author of The Digital Cat 
> My profile on About.me  - My GitHub
> page  - My Coderwall profile
> 
>
>
> 2013/10/2 Roberto López López  >
>
> Hi,
>
> I am extending a 3rd party model in my application, using
> multi-table inheritance. I can create an instance and modify it,
> but when I try to list the created objects at
> http://localhost:8000/en/admin/news/news/ , I am getting a nice
> exception:
>
> Traceback:
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/core/handlers/base.py"
> in get_response
>   140. response = response.render()
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/response.py"
> in render
>   105. self.content = self.rendered_content
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/response.py"
> in rendered_content
>   82. content = template.render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in render
>   140. return self._render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in _render
>   134. return self.nodelist.render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in render
>   830. bit = self.render_node(node, context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/debug.py"
> in render_node
>   74. return node.render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/loader_tags.py"
> in render
>   124. return compiled_parent._render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in _render
>   134. return self.nodelist.render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in render
>   830. bit = self.render_node(node, context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/debug.py"
> in render_node
>   74. return node.render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/loader_tags.py"
> in render
>   124. return compiled_parent._render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in _render
>   134. return self.nodelist.render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in render
>   830. bit = self.render_node(node, context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/debug.py"
> in render_node
>   74. return node.render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/loader_tags.py"
> in render
>   63. result = block.nodelist.render(context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in render
>   830. bit = self.render_node(node, context)
> File
> 
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/debug.py"
> in render_node
>   74. return node.render(context)
>

Re: model inheritance

2013-10-02 Thread Leonardo Giordani
Are you sure your DB has been synced after putting the ForeignKey(News) in
your Department model?
Can you post somewhere the following models: News, OldNews, Department?

Regards,

Leo

Leonardo Giordani
Author of The Digital Cat 
My profile on About.me  - My GitHub
page- My Coderwall
profile 


2013/10/2 Roberto López López 

>  Hi,
>
> I am extending a 3rd party model in my application, using multi-table
> inheritance. I can create an instance and modify it, but when I try to list
> the created objects at http://localhost:8000/en/admin/news/news/ , I am
> getting a nice exception:
>
> Traceback:
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/core/handlers/base.py"
> in get_response
>   140. response = response.render()
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/response.py"
> in render
>   105. self.content = self.rendered_content
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/response.py"
> in rendered_content
>   82. content = template.render(context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in render
>   140. return self._render(context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in _render
>   134. return self.nodelist.render(context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in render
>   830. bit = self.render_node(node, context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/debug.py"
> in render_node
>   74. return node.render(context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/loader_tags.py"
> in render
>   124. return compiled_parent._render(context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in _render
>   134. return self.nodelist.render(context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in render
>   830. bit = self.render_node(node, context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/debug.py"
> in render_node
>   74. return node.render(context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/loader_tags.py"
> in render
>   124. return compiled_parent._render(context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in _render
>   134. return self.nodelist.render(context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in render
>   830. bit = self.render_node(node, context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/debug.py"
> in render_node
>   74. return node.render(context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/loader_tags.py"
> in render
>   63. result = block.nodelist.render(context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in render
>   830. bit = self.render_node(node, context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/debug.py"
> in render_node
>   74. return node.render(context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/loader_tags.py"
> in render
>   63. result = block.nodelist.render(context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in render
>   830. bit = self.render_node(node, context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/debug.py"
> in render_node
>   74. return node.render(context)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
> in render
>   1185. _dict = func(*resolved_args, **resolved_kwargs)
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/contrib/admin/templatetags/admin_list.py"
> in result_list
>   286. 'results': list(results(cl))}
> File
> "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/contrib/admin/templatetags/admin_list.py"
> in results
>   264.

model inheritance

2013-10-02 Thread Roberto López López
Hi,

I am extending a 3rd party model in my application, using multi-table
inheritance. I can create an instance and modify it, but when I try to
list the created objects at http://localhost:8000/en/admin/news/news/ ,
I am getting a nice exception:

Traceback:
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/core/handlers/base.py"
in get_response
  140. response = response.render()
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/response.py"
in render
  105. self.content = self.rendered_content
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/response.py"
in rendered_content
  82. content = template.render(context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
in render
  140. return self._render(context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
in _render
  134. return self.nodelist.render(context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
in render
  830. bit = self.render_node(node, context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/debug.py"
in render_node
  74. return node.render(context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/loader_tags.py"
in render
  124. return compiled_parent._render(context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
in _render
  134. return self.nodelist.render(context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
in render
  830. bit = self.render_node(node, context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/debug.py"
in render_node
  74. return node.render(context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/loader_tags.py"
in render
  124. return compiled_parent._render(context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
in _render
  134. return self.nodelist.render(context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
in render
  830. bit = self.render_node(node, context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/debug.py"
in render_node
  74. return node.render(context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/loader_tags.py"
in render
  63. result = block.nodelist.render(context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
in render
  830. bit = self.render_node(node, context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/debug.py"
in render_node
  74. return node.render(context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/loader_tags.py"
in render
  63. result = block.nodelist.render(context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
in render
  830. bit = self.render_node(node, context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/debug.py"
in render_node
  74. return node.render(context)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/template/base.py"
in render
  1185. _dict = func(*resolved_args,
**resolved_kwargs)
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/contrib/admin/templatetags/admin_list.py"
in result_list
  286. 'results': list(results(cl))}
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/contrib/admin/templatetags/admin_list.py"
in results
  264. yield ResultList(None, items_for_result(cl, res,
None))
File

"/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/contrib/admin/templatetags/admin_list.py"
in __init__
  256. super(ResultList, 

Re: Model inheritance problem

2013-09-17 Thread George Lund
Ah okay, well I've never used that, I thought you were implying this could 
be a general Django question.

Maybe neo4django doesn't support model inheritance -- I took a look at 
their site briefly and couldn't see anything about it.

Sorry not to be more help...

On Tuesday, 17 September 2013 15:28:08 UTC+1, Antonio Mignolli wrote:
>
> Hmm, no, it does not work even without indexed=True, 
> my mistake.
> So the "issue" remains.
>
> Il giorno martedì 17 settembre 2013 16:17:04 UTC+2, Antonio Mignolli ha 
> scritto:
>>
>> Thanks, George, but as I said in the beginning, I'm using neo4django, 
>> which surely has StringProperty, otherwise I would have an 
>> AttributeError on StringProperty, which I don't have.
>>
>> I should have written:
>> from neo4django.db import models
>>
>> and 
>> ...
>> name = models.StringProperty(indexed=True)
>>
>> for completeness.
>>
>> I think I just discovered another neo4django issue,
>> in fact it works perfectly only if such attribute 
>> is not defined with indexed = True.
>>
>>
>> Il giorno martedì 17 settembre 2013 14:27:34 UTC+2, George Lund ha 
>> scritto:
>>>
>>>
>>> class MyBaseModel(models.NodeModel):
>>>>name=StringProperty()
>>>>class Meta:
>>>>abstract = True
>>>>
>>>>
>>> In Django you would need CharField or similar. StringProperty is a 
>>> Google App Engine thing? Cf 
>>> http://stackoverflow.com/questions/6132695/django-module-object-has-no-attribute-stringproperty
>>>
>>> So your base model has no field called "name".
>>>
>>> HTH
>>>
>>> George
>>>
>>

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Model inheritance problem

2013-09-17 Thread Antonio Mignolli
Hmm, no, it does not work even without indexed=True, 
my mistake.
So the "issue" remains.

Il giorno martedì 17 settembre 2013 16:17:04 UTC+2, Antonio Mignolli ha 
scritto:
>
> Thanks, George, but as I said in the beginning, I'm using neo4django, 
> which surely has StringProperty, otherwise I would have an 
> AttributeError on StringProperty, which I don't have.
>
> I should have written:
> from neo4django.db import models
>
> and 
> ...
> name = models.StringProperty(indexed=True)
>
> for completeness.
>
> I think I just discovered another neo4django issue,
> in fact it works perfectly only if such attribute 
> is not defined with indexed = True.
>
>
> Il giorno martedì 17 settembre 2013 14:27:34 UTC+2, George Lund ha scritto:
>>
>>
>> class MyBaseModel(models.NodeModel):
>>>name=StringProperty()
>>>class Meta:
>>>abstract = True
>>>
>>>
>> In Django you would need CharField or similar. StringProperty is a Google 
>> App Engine thing? Cf 
>> http://stackoverflow.com/questions/6132695/django-module-object-has-no-attribute-stringproperty
>>
>> So your base model has no field called "name".
>>
>> HTH
>>
>> George
>>
>

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Model inheritance problem

2013-09-17 Thread Antonio Mignolli
Thanks, George, but as I said in the beginning, I'm using neo4django, 
which surely has StringProperty, otherwise I would have an 
AttributeError on StringProperty, which I don't have.

I should have written:
from neo4django.db import models

and 
...
name = models.StringProperty(indexed=True)

for completeness.

I think I just discovered another neo4django issue,
in fact it works perfectly only if such attribute 
is not defined with indexed = True.


Il giorno martedì 17 settembre 2013 14:27:34 UTC+2, George Lund ha scritto:
>
>
> class MyBaseModel(models.NodeModel):
>>name=StringProperty()
>>class Meta:
>>abstract = True
>>
>>
> In Django you would need CharField or similar. StringProperty is a Google 
> App Engine thing? Cf 
> http://stackoverflow.com/questions/6132695/django-module-object-has-no-attribute-stringproperty
>
> So your base model has no field called "name".
>
> HTH
>
> George
>

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Model inheritance problem

2013-09-17 Thread George Lund


> class MyBaseModel(models.NodeModel):
>name=StringProperty()
>class Meta:
>abstract = True
>
>
In Django you would need CharField or similar. StringProperty is a Google 
App Engine thing? Cf 
http://stackoverflow.com/questions/6132695/django-module-object-has-no-attribute-stringproperty

So your base model has no field called "name".

HTH

George

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.


Model inheritance problem

2013-09-15 Thread Antonio Mignolli
Hi, I posted something similar also to italian Django-it group.

I'm using neo4django, but I want to understand things in a more 
generic way.

My case:

class MyBaseModel(models.NodeModel):
   name=StringProperty()
   class Meta:
   abstract = True

NodeModel it's a graph Node, like a record in a relational DB.

I inherit from MyBaseModel:

class User(MyBaseModel):
email=StringProperty()

I wish I could do the following:

Tony=User.objects.create(name="Tony",email="t...@anymail.bah")

but I got the error:
TypeError: 'name' is an invalid keyword argument for this function

Should I write the __init__?
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.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Model inheritance, implicit OneToOneField and stray inherited reverse relations

2013-06-12 Thread Benjamin Wohlwend
Hi Tom,

On Wednesday, June 12, 2013 10:25:24 AM UTC+2, Tomáš Ehrlich wrote:
>
> Hi Benjamin, 
> you can create explicit OneToOne field with parent_link=True 
>
> https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.OneToOneField.parent_link
>  
>
> Then you can set different related_name for each model. 
>
>
>
yes, that seems to work. Thank you! The small problem with this solution is 
that it has to be done for every CMSPlugin subclass (hundreds, if not 
thousands in the wild), or at least for those with common names.

Benjamin

-- 
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?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Model inheritance, implicit OneToOneField and stray inherited reverse relations

2013-06-12 Thread Tomas Ehrlich
Hi Benjamin,
you can create explicit OneToOne field with parent_link=True
https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.OneToOneField.parent_link

Then you can set different related_name for each model.


Cheers,
  Tom


Dne Wed, 12 Jun 2013 01:10:40 -0700 (PDT)
Benjamin  Wohlwend <piquad...@gmail.com> napsal(a):

> Hi,
> 
> I have a bit of a problem with inherited reverse relations and django model 
> inheritance. Consider these models:
> 
> 
> class Content(models.Model):
> display = models.BooleanField()
> 
> 
> class Link(Content):
> url = models.URLField()
> 
> 
> class Teaser(Content):
> text = models.TextField()
> link = models.URLField()
> 
> 
> As we all know, Django uses an implicit OneToOneField for model 
> inheritance. This OneToOneField generates accessors for the reverse 
> relation, which in this case means that objects of the type Content will 
> have a "link" and a "teaser" attribute to access the other side of the 
> one-to-one relation. These attributes are, of course, inherited to the 
> Content subclasses, meaning that Link and Teaser also will have those 
> accessors. But wait, Teaser already defines a link attribute! We got 
> ourselves a nice little name clash.
> 
> While it's perfectly according to the rules of inheritance for Link and 
> Teaser to inherit the "link" and "teaser" reverse relations accessors, it 
> is also a bit nonsensical in this case. As far as I can tell, it's not 
> possible to suppress the creation of these accessors when defining the 
> model inheritance. Any ideas how to get around this (other than "just 
> rename the link attribute in Teaser, silly!")?
> 
> Benjamin
> 
> P.S.: the real use case here is django CMS, with its content plugins all 
> inheriting from a CMSPlugin base class. Since there are e.g. subclasses 
> called Text, Link, and Picture, it's not possible to use field names called 
> "text", "link", or "picture" in a CMSPlugin subclass, which is frustrating 
> and hard to explain to our users.
> 



S pozdravem
  Tomáš Ehrlich

Email:  tomas.ehrl...@gmail.com
Tel:+420 608 219 889
Jabber: elv...@jabber.cz

"Půjdu kamkoliv, pokud je to kupředu." - J. London

-- 
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?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Model inheritance, implicit OneToOneField and stray inherited reverse relations

2013-06-12 Thread Benjamin Wohlwend
Hi,

I have a bit of a problem with inherited reverse relations and django model 
inheritance. Consider these models:


class Content(models.Model):
display = models.BooleanField()


class Link(Content):
url = models.URLField()


class Teaser(Content):
text = models.TextField()
link = models.URLField()


As we all know, Django uses an implicit OneToOneField for model 
inheritance. This OneToOneField generates accessors for the reverse 
relation, which in this case means that objects of the type Content will 
have a "link" and a "teaser" attribute to access the other side of the 
one-to-one relation. These attributes are, of course, inherited to the 
Content subclasses, meaning that Link and Teaser also will have those 
accessors. But wait, Teaser already defines a link attribute! We got 
ourselves a nice little name clash.

While it's perfectly according to the rules of inheritance for Link and 
Teaser to inherit the "link" and "teaser" reverse relations accessors, it 
is also a bit nonsensical in this case. As far as I can tell, it's not 
possible to suppress the creation of these accessors when defining the 
model inheritance. Any ideas how to get around this (other than "just 
rename the link attribute in Teaser, silly!")?

Benjamin

P.S.: the real use case here is django CMS, with its content plugins all 
inheriting from a CMSPlugin base class. Since there are e.g. subclasses 
called Text, Link, and Picture, it's not possible to use field names called 
"text", "link", or "picture" in a CMSPlugin subclass, which is frustrating 
and hard to explain to our users.

-- 
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?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Multiple model inheritance

2013-01-06 Thread nkryptic
yes, yes, no and yes. Abstract models should inherit form models.Model.  
Abstract models should always have a Meta class with abstract=True.  The 
order matters when it comes to shared functionality.  Here's how I would 
code those models you had:

class Taggable(models.Model):
tag = models.CharField()
class Meta:
abstract = True

class Visible(models.Model):
visible = models.BooleanField()
class Meta:
abstract = True

class SomeFullModel(Taggable, Visible):
otherfield = models.CharField()


If you override a method on all three of those classes (e.g. the save 
method) and in each of them, call super(...).save(), then the order be:
SomeFullModel.save() => Taggable.save() => Visible.save() => 
models.Model.save()

As to how the Meta class is inherited, I'll point you 
to https://docs.djangoproject.com/en/1.4/topics/db/models/#meta-inheritance
 

On Monday, December 31, 2012 8:12:03 AM UTC-5, Mattias Linnap wrote:
>
> Hi all, 
>
> I would like to define multiple abstract base models with small set of 
> fields each. The "real" models inherit from multiple mixins to add the 
> fields. 
>
> For example: 
> class Taggable(?): 
> tag = models.CharField() 
> class Visible(?): 
> visible = models.BooleanField() 
> class SomeFullModel(?, Taggable, Visible): 
> otherfield = models.CharField() 
>
> With this use case: 
> * should the abstract models inherit from models.Model, or be a plain 
> Python class inheriting from object? 
> * should all or any of the abstract models have a class Meta with 
> abstract=True? 
> * should the final real model inherit from models.Model (probably 
> required if all the mixins are plain classes), or inherit from the 
> first mixin that is an abstract model? 
> * does the order of the base classes in SomeFullModel matter? 
>
> Thanks, 
>
> Mattias 
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/9luopcnKn1MJ.
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: Multiple model inheritance

2013-01-05 Thread Peter of the Norse
I’m not sure that’s possible. Even abstract Models do magic in the background. 
Specifically there's the _meta class attribute that gets inherited. If you were 
to try it, only one of the _metas would be included.

On Dec 31, 2012, at 6:12 AM, Mattias Linnap wrote:

> Hi all,
> 
> I would like to define multiple abstract base models with small set of
> fields each. The "real" models inherit from multiple mixins to add the
> fields.
> 
> For example:
> class Taggable(?):
>tag = models.CharField()
> class Visible(?):
>visible = models.BooleanField()
> class SomeFullModel(?, Taggable, Visible):
>otherfield = models.CharField()
> 
> With this use case:
> * should the abstract models inherit from models.Model, or be a plain
> Python class inheriting from object?
> * should all or any of the abstract models have a class Meta with
> abstract=True?
> * should the final real model inherit from models.Model (probably
> required if all the mixins are plain classes), or inherit from the
> first mixin that is an abstract model?
> * does the order of the base classes in SomeFullModel matter?
> 
> Thanks,
> 
> Mattias
> 
> -- 
> 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.
> 

Peter of the Norse
rahmc...@radio1190.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-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.



Multiple model inheritance

2012-12-31 Thread Mattias Linnap
Hi all,

I would like to define multiple abstract base models with small set of
fields each. The "real" models inherit from multiple mixins to add the
fields.

For example:
class Taggable(?):
tag = models.CharField()
class Visible(?):
visible = models.BooleanField()
class SomeFullModel(?, Taggable, Visible):
otherfield = models.CharField()

With this use case:
* should the abstract models inherit from models.Model, or be a plain
Python class inheriting from object?
* should all or any of the abstract models have a class Meta with
abstract=True?
* should the final real model inherit from models.Model (probably
required if all the mixins are plain classes), or inherit from the
first mixin that is an abstract model?
* does the order of the base classes in SomeFullModel matter?

Thanks,

Mattias

-- 
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-typed-models - sane single-table model inheritance

2012-02-19 Thread Craig de Stigter
In May last year I posted this 
topic<https://groups.google.com/d/topic/django-developers/1LA98LjNz-g/discussion>on
 django-developers.

We wanted a way to do proxy-model inheritance, while preserving the type of 
each object when it goes in and out of the database.

Unable to find anything that did what I wanted, I wrote my own! It was 
basically finished by June last year but I finally open-sourced it:

https://github.com/craigds/django-typed-models

Basically you can just define a base model, with database fields, and then 
inherit from it as much as you want. The inherited models all become proxy 
models - they only define in-python behavior, they can't define database 
fields.

Everything gets stored in one table, and retrieving objects from the 
database will result in them having the correct model class. A single 
queryset of a superclass might result in the retrieval of multiple types of 
subclasses, all in one query.

See the readme on that github link for an example. Please let me know what 
you think! And file issues if you have some.

Cheers

Craig de Stigter
Koordinates Ltd

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/Ff9H0nAZHbAJ.
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: Model Inheritance Downcasting

2011-11-16 Thread Torsten Bronger
Hallöchen!

Bastian Kuberek writes:

> [...]
>
> What I need is to be able to query the Widget class and get back
> subclasses based on their type:
>
 widgets = Widget.objects.all()
 print widgets
> [ 5>,]

We do this very reliably with
http://djangosnippets.org/snippets/2091/ but I find
https://github.com/carljm/django-model-utils/blob/master/README.rst
very interesting, too.

This is a frequently-requested feature with many implementations,
yet there is no canonical solution in Django, unfortunately.

Tschö,
Torsten.

-- 
Torsten BrongerJabber ID: torsten.bron...@jabber.rwth-aachen.de
  or http://bronger-jmp.appspot.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-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: Model Inheritance Downcasting

2011-11-16 Thread Tom Evans
On Wed, Nov 16, 2011 at 4:43 PM, Bastian Kuberek  wrote:
> Hi,
> I have looked a lot and have not yet figured out how to accomplish this.
> Let me show with an example what I am trying to accomplish.
>
> 

http://code.google.com/p/django-polymorphic-models/

Cheers

Tom

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



Model Inheritance Downcasting

2011-11-16 Thread Bastian Kuberek
Hi,

I have looked a lot and have not yet figured out how to accomplish this.

Let me show with an example what I am trying to accomplish.


class WidgetType(models.Model):
"""WidgetType categorizes the type of Widget"""

name = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, editable=False)

class Meta:
db_table = u'widget_type'

class Widget(models.Model):
"""Widget is a component of WidgetType type that renders a DataStream 
on a defined Dashboard"""

widget_type = models.ForeignKey(WidgetType)

name = models.CharField(max_length=255, null=True, blank=True)

class Meta:
db_table = u'widget'

class LineChart(Widget):
"""Line Chart Widget Proxy"""

class Meta:
proxy = True

def save(self, *args, **kwargs):
self.widget_type = WidgetType.objects.get(slug='line-chart')
super(LineChart, self).save(*args, **kwargs)


As you can see above, there are 3 classes (simplified). I have 2 tables: 
"widget_type" and "widget". When creating an instance of Widget, one must 
select the type of widget. So one could create instances of LineChart, 
BarChart, ScatterChart, etc and all of this models would persist to the 
same table, "widget".

The issues I have with this design is that one doesn't always know what 
type of widget it is so the following is not possible:

widgets = LineChart.objects.all() 


What I need is to be able to query the Widget class and get back subclasses 
based on their type:

>>> widgets = Widget.objects.all()
>>> print widgets
[,]



Any help appreciated.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/aQQojIweoPoJ.
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: Model Inheritance and ModelForms

2011-10-29 Thread Alex
Tom,

Thanks for the quick reply! However, when I tried that I got an error
saying that inventoryitem "is an invalid keyword argument for this
function". I fixed this by manually specifying the OneToOneField
relationship with the parent class as inventoryItem and setting
parent_link=True. With that in place, I get errors about InventoryItem
fields not being allowed to be null within InventoryBook. This doesn't
make sense to me since InventoryBook should only have a link to the
parent and its own local book-specific fields - not the fields
previously declared in the parent InventoryItem. I have not declared
any models to be abstract (and in fact have not declared Meta: at
all).

If I need to manually specify all of the InventoryItem fields again in
the constructor of the InventoryBook, I can. But doing so seems to
defeat the purpose of using inheritance to begin with. Is there
something I'm still overlooking?

Thanks again,

-Alex

On Oct 28, 5:53 am, Tom Evans  wrote:
> On Fri, Oct 28, 2011 at 7:50 AM, Alex  wrote:
> > I've been scouring Google and the Django documentation and I can't
> > figure out how to do this. I'm working on an inventory management
> > system for my shop. My inventory models.py similar to the following:
>
> >    class ItemType( models.Model ):
> >        def __unicode__( self ):
> >            return "blah blah blah"
>
> >        itemType = models.CharField( max_length = 32 )
> >        isBook = models.BooleanField()
>
> >    class InventoryItem( models.Model ):
> >        def __unicode__( self ):
> >            return "blah"
>
> >        itemType = models.ForeignKey( ItemType )
> >        description = models.CharField( max_length = 256 )
>
> >    class InventoryBook( InventoryItem ):
> >        def __unicode__( self ):
> >            return "blah blah"
>
> >        title = models.CharField( max_length = 64 )
>
> > In my web app, I create a ModelForm based on InventoryItem and present
> > that to the user. Upon submission, the POST data is used to create an
> > instance of InventoryItem. I then check to see if
> > inventoryItem.itemType.isBook() is True - if True, I want to cast
> > inventoryItem to an InventoryBook type so I can set the extra fields
> > and call save() so that it creates records in both tables in the MySQL
> > database.
>
> > I started trying to add a method to InventoryItem that would return an
> > InventoryBook instance after being given the title string, but that
> > doesn't work because Python doesn't have prototyping/forward
> > declarations.
>
> > Am I approaching this completely wrong, or am I just overlooking
> > something simple? Any advice or links to relevant documentation would
> > be *much* appreciated. Thanks!
>
> > -Alex
>
> If you have an InventoryItem which should be an InventoryBook, you
> need to create the InventoryBook, not cast to it.
>
> item = …
> if item.itemType.isBook():
>   book = InventoryBook.objects.create(inventoryitem=item, title=…)
>
> Inheritance like this in django isn't really like OOO inheritance,
> InventoryBook just magically gains a OneToOneField back to
> InventoryItem called inventoryitem.
>
> Cheers
>
> Tom

-- 
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: Model Inheritance and ModelForms

2011-10-28 Thread Tom Evans
On Fri, Oct 28, 2011 at 7:50 AM, Alex  wrote:
> I've been scouring Google and the Django documentation and I can't
> figure out how to do this. I'm working on an inventory management
> system for my shop. My inventory models.py similar to the following:
>
>    class ItemType( models.Model ):
>        def __unicode__( self ):
>            return "blah blah blah"
>
>        itemType = models.CharField( max_length = 32 )
>        isBook = models.BooleanField()
>
>    class InventoryItem( models.Model ):
>        def __unicode__( self ):
>            return "blah"
>
>        itemType = models.ForeignKey( ItemType )
>        description = models.CharField( max_length = 256 )
>
>    class InventoryBook( InventoryItem ):
>        def __unicode__( self ):
>            return "blah blah"
>
>        title = models.CharField( max_length = 64 )
>
> In my web app, I create a ModelForm based on InventoryItem and present
> that to the user. Upon submission, the POST data is used to create an
> instance of InventoryItem. I then check to see if
> inventoryItem.itemType.isBook() is True - if True, I want to cast
> inventoryItem to an InventoryBook type so I can set the extra fields
> and call save() so that it creates records in both tables in the MySQL
> database.
>
> I started trying to add a method to InventoryItem that would return an
> InventoryBook instance after being given the title string, but that
> doesn't work because Python doesn't have prototyping/forward
> declarations.
>
> Am I approaching this completely wrong, or am I just overlooking
> something simple? Any advice or links to relevant documentation would
> be *much* appreciated. Thanks!
>
> -Alex
>

If you have an InventoryItem which should be an InventoryBook, you
need to create the InventoryBook, not cast to it.

item = …
if item.itemType.isBook():
  book = InventoryBook.objects.create(inventoryitem=item, title=…)

Inheritance like this in django isn't really like OOO inheritance,
InventoryBook just magically gains a OneToOneField back to
InventoryItem called inventoryitem.

Cheers

Tom

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



Model Inheritance and ModelForms

2011-10-28 Thread Alex
I've been scouring Google and the Django documentation and I can't
figure out how to do this. I'm working on an inventory management
system for my shop. My inventory models.py similar to the following:

class ItemType( models.Model ):
def __unicode__( self ):
return "blah blah blah"

itemType = models.CharField( max_length = 32 )
isBook = models.BooleanField()

class InventoryItem( models.Model ):
def __unicode__( self ):
return "blah"

itemType = models.ForeignKey( ItemType )
description = models.CharField( max_length = 256 )

class InventoryBook( InventoryItem ):
def __unicode__( self ):
return "blah blah"

title = models.CharField( max_length = 64 )

In my web app, I create a ModelForm based on InventoryItem and present
that to the user. Upon submission, the POST data is used to create an
instance of InventoryItem. I then check to see if
inventoryItem.itemType.isBook() is True - if True, I want to cast
inventoryItem to an InventoryBook type so I can set the extra fields
and call save() so that it creates records in both tables in the MySQL
database.

I started trying to add a method to InventoryItem that would return an
InventoryBook instance after being given the title string, but that
doesn't work because Python doesn't have prototyping/forward
declarations.

Am I approaching this completely wrong, or am I just overlooking
something simple? Any advice or links to relevant documentation would
be *much* appreciated. Thanks!

-Alex

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



Model Inheritance and methods

2011-08-20 Thread CrabbyPete
I have the following models:

class Deal(models.Model):
"""
Deal is a deal for  Interest. There should only be one
deal for each Interest pair
"""
interest = models.ForeignKey( Interest )
max_sell = models.IntegerField(default = 1)

def terms(self):
return self.term_set.all()

class Term( models.Model ):
"""
A Term are the terms of a Deal. There can be many Terms for each
Deal
"""
deal  = models.ForeignKey( Deal )
canceled  = models.BooleanField(default = False)
cost  = models.CharField( max_length = 10, blank = True, null
= True )
buyer = models.ForeignKey( User, blank = True, null = True )

def execute(self, **kwargs):
pass

class Expire( Term ):
"""
Subclass of Term that is good until an expiration date
"""
date= models.DateField()

def execute(self):
if self.buyer == None or self.canceled:
return False

delta = self.date - date.today()
if delta.days >= 0:
return True
return False

def __unicode__(self, **kwargs):
return ''

class Cancel( Term ):
"""
Subclass of Term that the Term is good until canceled
"""
def execute(self):
if self.buyer == None or self.canceled:
return False
return True

def __unicode__(self):
return ''


I want to do the following:
for term in deal.terms()
 if term.execute():
do something


My thought was the term.execute method would be overridden and the
type of term, either cancel's or expire's execute method would occur,
but it only executes the term.execute()

I can get around it by having the following as the term execute, but
its ugly
def execute(self):
try:
   term.cancel.execute()
except:
   pass
try:
  term.expire.execute()
except:
   pass

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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: What are the advantages of Model inheritance?

2011-06-24 Thread bruno desthuilliers
On Jun 23, 11:40 pm, Micky Hulse <rgmi...@gmail.com> wrote:
> On Thu, Jun 23, 2011 at 2:17 PM, bruno desthuilliers
>
> <bruno.desthuilli...@gmail.com> wrote:
> > FWIW, I have been using model inheritance - abstract and concrete - in
> > half a dozen projects, with about 30 model subclasses in one of them,
> > and it JustWorks(tm).
>
> That sounds pretty sweet! :D

That's not. In fact it's rather ugly, but I had few other choice -
this is a mirroring of a Plone-based EDM system, so I have a base
"Content" class and one subclasses for each and every AT Content type
in the system... And then I'm using proxy models on top of this to get
something I can work with. Kind of a mess, but hey, it works.

> I would love to see some examples.

You wouldn't like to see this one, believe me. It's a real
monstruosity.

> I have been using abstract models for some of my projects... I find
> them extremely useful

So do I. Being able to factor out a subset of related fields and
behaviours can greatly simplify some stuff.

>
> https://gist.github.com/1043698
>
> It works for me... Of course, I am still a noobie to Python/Django, so
> may the feedback be kind. :: crosses fingers :: :D

You may be interested in the "auto_now" and "auto_now_add" arguments
to Date and DateTime fields.




-- 
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: What are the advantages of Model inheritance?

2011-06-23 Thread Matthew Gardner
I think you're right, Rich, that when you query on a table, it'll only grab
the results for that table.  So when you do user.post_set.all(), it only
creates Post objects, because it only pulls data from that one table.  When
you do user.betterpost_set.all(), the reason you don't see anything is that
that line of code raises an error, because user doesn't have a
"betterpost_set" attribute.  The templating language hides the error for
you, so you just get no output.

So, yeah, if you want real polymorphic inheritance, you aren't going to get
it with django, as far as I know.  And in that regard, you're probably
better off not using inheritance so that you won't expect those kinds of
features.  Abstract inheritance has its benefits in code simplification, and
I can imagine that multi-table inheritance also has some uses, but they are
not the ones that you typically expect from inheritance in python.

In case you aren't aware, to actually get at the subclass instance from a
superclass instance in django, you have to do something like this:

try:
bp = post.betterpost
# do stuff with bp
except BetterPost.DoesNotExist:
pass

To get the behavior you want in that template, you need to manually create
the list of posts in the python code, doing something like the following:

posts_queryset = user.post_set.all()
posts = []
for post in posts_queryset:
try:
bp = post.betterpost
posts.append(bp)
except BetterPost.DoesNotExist:
posts.append(post)
context['posts'] = posts

You can imagine that if you have several subclasses of Post this could get
pretty annoying.  I'd probably write a separate method to return the most
specific instance of an object that I could.

On Thu, Jun 23, 2011 at 5:54 PM, Rich Jones <miser...@gmail.com> wrote:

> Even ignoring the select_related then - the fact is that
>
> user.post_set works and user.betterpost_set won't work, seemingly as
> the result of using model inheritance.
>
> Perhaps I could get all of the posts (post and betterposts) and then
> filter by time? Does that make sense / is there a way to do that in
> the template?
>
> R
>
> On Jun 23, 5:40 pm, Micky Hulse <rgmi...@gmail.com> wrote:
> > On Thu, Jun 23, 2011 at 2:17 PM, bruno desthuilliers
> >
> > <bruno.desthuilli...@gmail.com> wrote:
> > > FWIW, I have been using model inheritance - abstract and concrete - in
> > > half a dozen projects, with about 30 model subclasses in one of them,
> > > and it JustWorks(tm).
> >
> > That sounds pretty sweet! :D
> >
> > I would love to see some examples.
> >
> > I have been using abstract models for some of my projects... I find
> > them extremely useful:
> >
> > https://gist.github.com/1043698
> >
> > It works for me... Of course, I am still a noobie to Python/Django, so
> > may the feedback be kind. :: crosses fingers :: :D
>
> --
> 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.
>
>

-- 
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: What are the advantages of Model inheritance?

2011-06-23 Thread Rich Jones
Even ignoring the select_related then - the fact is that

user.post_set works and user.betterpost_set won't work, seemingly as
the result of using model inheritance.

Perhaps I could get all of the posts (post and betterposts) and then
filter by time? Does that make sense / is there a way to do that in
the template?

R

On Jun 23, 5:40 pm, Micky Hulse <rgmi...@gmail.com> wrote:
> On Thu, Jun 23, 2011 at 2:17 PM, bruno desthuilliers
>
> <bruno.desthuilli...@gmail.com> wrote:
> > FWIW, I have been using model inheritance - abstract and concrete - in
> > half a dozen projects, with about 30 model subclasses in one of them,
> > and it JustWorks(tm).
>
> That sounds pretty sweet! :D
>
> I would love to see some examples.
>
> I have been using abstract models for some of my projects... I find
> them extremely useful:
>
> https://gist.github.com/1043698
>
> It works for me... Of course, I am still a noobie to Python/Django, so
> may the feedback be kind. :: crosses fingers :: :D

-- 
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: What are the advantages of Model inheritance?

2011-06-23 Thread Micky Hulse
On Thu, Jun 23, 2011 at 2:17 PM, bruno desthuilliers
<bruno.desthuilli...@gmail.com> wrote:
> FWIW, I have been using model inheritance - abstract and concrete - in
> half a dozen projects, with about 30 model subclasses in one of them,
> and it JustWorks(tm).

That sounds pretty sweet! :D

I would love to see some examples.

I have been using abstract models for some of my projects... I find
them extremely useful:

https://gist.github.com/1043698

It works for me... Of course, I am still a noobie to Python/Django, so
may the feedback be kind. :: crosses fingers :: :D

-- 
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: What are the advantages of Model inheritance?

2011-06-23 Thread bruno desthuilliers
On Jun 23, 8:24 pm, Rich Jones <miser...@gmail.com> wrote:
> Other than the convenience of writing them, I can't seem to find any
> advantages of using model inheritance.

Really ???


> Please allow me to explain the trouble I am having with an example.
> Suppose,
>
> class Post(models.Model):
>     title = models.CharField(max_length=200)
>     user_owner_id = models.ForeignKey(User)
>
>     def __unicode__(self):
>         return self.title
>
> class BetterPost(Post):
>     description = models.CharField(max_length=200)
>
>     def __unicode__(self):
>         return self.title

You don't need to redifine __unicode__ here.

> Now, in the template:
>
> {% with profile.user.post_set.select_related as posts %}

For what you're doing in the template and given your models, the
select_related is totally useless.

>     {% for post in posts %}
>         {{post}}
>     {% empty %}
>         No posts!
>     {% endfor %}
> {% endwith %}
>
> {% with profile.user.betterpost_set.select_related as posts %}
>     {% for post in posts %}
>         {{post}}
>     {% empty %}
>         No posts!
>     {% endfor %}
> {% endwith %}
>
> If there are 2 'Posts' and 1 'BetterPost',

Belonging to the same user ???

> the template code will
> print all of the posts in the first loop, then none in the second loop
> set.

If so, please inspect your data, as there's obviously something wrong.
With your data, I mean.

> So why would I use model inheritance if this is the kind of behavior I
> can expect? If I can't get a set and can't access the fields, why
> wouldn't I just copy the fields into BetterPost rather than extending
> Post?

If that was the case, then model inheritance would indeed be a plain
waste of time. Now, just a simple question: do you really think anyone
would have wasted time implementing model inheritance, testing it, and
documenting it if that was all you could "expect" from it ?

FWIW, I have been using model inheritance - abstract and concrete - in
half a dozen projects, with about 30 model subclasses in one of them,
and it JustWorks(tm).

-- 
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: What are the advantages of Model inheritance?

2011-06-23 Thread Cal Leeming [Simplicity Media Ltd]
Here you go :)

https://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models

On Thu, Jun 23, 2011 at 10:12 PM, Rich Jones <miser...@gmail.com> wrote:

> Where would _meta need to go?
>
> This code does appear to work the way I am describing it, this is just
> a slightly stripped down of a real application I have made.
>
> R
>
> On Jun 23, 4:59 pm, "Cal Leeming [Simplicity Media Ltd]"
> <cal.leem...@simplicitymedialtd.co.uk> wrote:
> > I might be wrong here, but I'm fairly sure that the below example you
> pasted is invalid code (i.e. you need to add a proxy _meta??).
> > My apologies if I'm wrong though, as I have never encountered a need to
> do this before, and just going off vague memory.
> > Cal
> > On 23/06/2011 19:24, Rich Jones wrote:Other than the convenience of
> writing them, I can't seem to find any advantages of using model
> inheritance. Please allow me to explain the trouble I am having with an
> example. Suppose, class Post(models.Model): title =
> models.CharField(max_length=200) user_owner_id = models.ForeignKey(User) def
> __unicode__(self): return self.title class BetterPost(Post): description =
> models.CharField(max_length=200) def __unicode__(self): return self.title
> Now, in the template: {% with profile.user.post_set.select_related as posts
> %} {% for post in posts %} {{post}} {% empty %} No posts! {% endfor %} {%
> endwith %} {% with profile.user.betterpost_set.select_related as posts %} {%
> for post in posts %} {{post}} {% empty %} No posts! {% endfor %} {% endwith
> %} If there are 2 'Posts' and 1 'BetterPost', the template code will print
> all of the posts in the first loop, then none in the second loop set. So why
> would I use model inheritance if this is the kind of behavior I can expect?
> If I can't get a set and can't access the fields, why wouldn't I just copy
> the fields into BetterPost rather than extending Post? Thank you for
> reading! R
>
> --
> 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.
>
>

-- 
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: What are the advantages of Model inheritance?

2011-06-23 Thread Rich Jones
Where would _meta need to go?

This code does appear to work the way I am describing it, this is just
a slightly stripped down of a real application I have made.

R

On Jun 23, 4:59 pm, "Cal Leeming [Simplicity Media Ltd]"
<cal.leem...@simplicitymedialtd.co.uk> wrote:
> I might be wrong here, but I'm fairly sure that the below example you pasted 
> is invalid code (i.e. you need to add a proxy _meta??).
> My apologies if I'm wrong though, as I have never encountered a need to do 
> this before, and just going off vague memory.
> Cal
> On 23/06/2011 19:24, Rich Jones wrote:Other than the convenience of writing 
> them, I can't seem to find any advantages of using model inheritance. Please 
> allow me to explain the trouble I am having with an example. Suppose, class 
> Post(models.Model): title = models.CharField(max_length=200) user_owner_id = 
> models.ForeignKey(User) def __unicode__(self): return self.title class 
> BetterPost(Post): description = models.CharField(max_length=200) def 
> __unicode__(self): return self.title Now, in the template: {% with 
> profile.user.post_set.select_related as posts %} {% for post in posts %} 
> {{post}} {% empty %} No posts! {% endfor %} {% endwith %} {% with 
> profile.user.betterpost_set.select_related as posts %} {% for post in posts 
> %} {{post}} {% empty %} No posts! {% endfor %} {% endwith %} If there are 2 
> 'Posts' and 1 'BetterPost', the template code will print all of the posts in 
> the first loop, then none in the second loop set. So why would I use model 
> inheritance if this is the kind of behavior I can expect? If I can't get a 
> set and can't access the fields, why wouldn't I just copy the fields into 
> BetterPost rather than extending Post? Thank you for reading! R

-- 
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: What are the advantages of Model inheritance?

2011-06-23 Thread Cal Leeming [Simplicity Media Ltd]


  
  
I might be wrong here, but I'm fairly sure that the below example
you pasted is invalid code (i.e. you need to add a proxy _meta??).

My apologies if I'm wrong though, as I have never encountered a need
to do this before, and just going off vague memory.

Cal

On 23/06/2011 19:24, Rich Jones wrote:

  Other than the convenience of writing them, I can't seem to find any
advantages of using model inheritance.

Please allow me to explain the trouble I am having with an example.
Suppose,

class Post(models.Model):
title = models.CharField(max_length=200)
user_owner_id = models.ForeignKey(User)

def __unicode__(self):
return self.title

class BetterPost(Post):
description = models.CharField(max_length=200)

def __unicode__(self):
return self.title

Now, in the template:

{% with profile.user.post_set.select_related as posts %}
{% for post in posts %}
{{post}}
{% empty %}
No posts!
{% endfor %}
{% endwith %}

{% with profile.user.betterpost_set.select_related as posts %}
{% for post in posts %}
{{post}}
{% empty %}
No posts!
{% endfor %}
{% endwith %}

If there are 2 'Posts' and 1 'BetterPost', the template code will
print all of the posts in the first loop, then none in the second loop
set.

So why would I use model inheritance if this is the kind of behavior I
can expect? If I can't get a set and can't access the fields, why
wouldn't I just copy the fields into BetterPost rather than extending
Post?

Thank you for reading!
R




  




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




What are the advantages of Model inheritance?

2011-06-23 Thread Rich Jones
Other than the convenience of writing them, I can't seem to find any
advantages of using model inheritance.

Please allow me to explain the trouble I am having with an example.
Suppose,

class Post(models.Model):
title = models.CharField(max_length=200)
user_owner_id = models.ForeignKey(User)

def __unicode__(self):
return self.title

class BetterPost(Post):
description = models.CharField(max_length=200)

def __unicode__(self):
return self.title

Now, in the template:

{% with profile.user.post_set.select_related as posts %}
{% for post in posts %}
{{post}}
{% empty %}
No posts!
{% endfor %}
{% endwith %}

{% with profile.user.betterpost_set.select_related as posts %}
{% for post in posts %}
{{post}}
{% empty %}
No posts!
{% endfor %}
{% endwith %}

If there are 2 'Posts' and 1 'BetterPost', the template code will
print all of the posts in the first loop, then none in the second loop
set.

So why would I use model inheritance if this is the kind of behavior I
can expect? If I can't get a set and can't access the fields, why
wouldn't I just copy the fields into BetterPost rather than extending
Post?

Thank you for reading!
R

-- 
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: Abstract Model Inheritance and Custom Managers?

2011-01-13 Thread Marc Aymerich
On Thu, Jan 13, 2011 at 9:10 PM, ringemup <ringe...@gmail.com> wrote:
> If a manager is defined on an abstract model, do non-abstract child
> models inherit the manager?

http://docs.djangoproject.com/en/dev/topics/db/managers/#custom-managers-and-model-inheritance
-- 
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-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.



Abstract Model Inheritance and Custom Managers?

2011-01-13 Thread ringemup
If a manager is defined on an abstract model, do non-abstract child
models inherit the manager?

-- 
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: problems with model inheritance if base class is not abstract

2010-11-21 Thread Marco Ferragina
Mmm yes it seems you are right. But I think this is a bit confusing
thinking about object oriented programming, it is not? Then the only
way to avoid this seems to be use an abstract base class or use some
not so clean way to simulate this behavior.



On 21 Nov, 01:36, Ramiro Morales  wrote:
> On Sat, Nov 20, 2010 at 7:59 AM, marco.ferrag...@gmail.com
>
>
>
>
>
>
>
>
>
>  wrote:
> > Hi all! I'm new to django and I'm experimenting with models but I have
> > some trouble. I've minimized my problem to this code:
>
> > class TestBase(models.Model):
> >    base = models.CharField(max_length=255)
>
> > from django.contrib import admin
> > class TestA(TestBase):
> >    testb = models.CharField(max_length=255)
>
> > admin.site.register(TestA)
>
> > class TestB(TestBase):
> >    testc = models.CharField(max_length=255)
>
> > admin.site.register(TestB)
>
> > Trying to add TestA instances from admin interface I have this error:
> > Cannot assign "''": "TestA.testb" must be a "TestB" instance.
>
> > why testb should be a TestB instance?? It's a simple field!
>
> I suspect this is because of something that is described in the MTI docs:
>
> http://docs.djangoproject.com/en/1.2/topics/db/models/#multi-table-in...
>
> Translated to you example the relevant paragraph says:
>
> "If you have a TestBase that is also a TestB, you can get from the TestBase
> object to the TestB object by using the lower-case version of the model name:
>
> >>> p = TestBase.objects.get(id=12)
>
> # If p is a TestB object, this will give the child class:>>> p.testb
>
> 
>
> "
>
> The TestA model is inheriting that 'testb' accesor from TestBase to TestB
> and it is clashing with the identically named field.
>
> --
> Ramiro Morales

-- 
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: problems with model inheritance if base class is not abstract

2010-11-20 Thread Joseph (Driftwood Cove Designs)
Ramiro - you made my day.  Somehow I missed this little tid bit in the
docs - what a super handy feature!! thank you.

On Nov 20, 4:36 pm, Ramiro Morales  wrote:
> On Sat, Nov 20, 2010 at 7:59 AM, marco.ferrag...@gmail.com
>
>
>
>  wrote:
> > Hi all! I'm new to django and I'm experimenting with models but I have
> > some trouble. I've minimized my problem to this code:
>
> > class TestBase(models.Model):
> >    base = models.CharField(max_length=255)
>
> > from django.contrib import admin
> > class TestA(TestBase):
> >    testb = models.CharField(max_length=255)
>
> > admin.site.register(TestA)
>
> > class TestB(TestBase):
> >    testc = models.CharField(max_length=255)
>
> > admin.site.register(TestB)
>
> > Trying to add TestA instances from admin interface I have this error:
> > Cannot assign "''": "TestA.testb" must be a "TestB" instance.
>
> > why testb should be a TestB instance?? It's a simple field!
>
> I suspect this is because of something that is described in the MTI docs:
>
> http://docs.djangoproject.com/en/1.2/topics/db/models/#multi-table-in...
>
> Translated to you example the relevant paragraph says:
>
> "If you have a TestBase that is also a TestB, you can get from the TestBase
> object to the TestB object by using the lower-case version of the model name:
>
> >>> p = TestBase.objects.get(id=12)
>
> # If p is a TestB object, this will give the child class:>>> p.testb
>
> 
>
> "
>
> The TestA model is inheriting that 'testb' accesor from TestBase to TestB
> and it is clashing with the identically named field.
>
> --
> Ramiro Morales

-- 
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: problems with model inheritance if base class is not abstract

2010-11-20 Thread Ramiro Morales
On Sat, Nov 20, 2010 at 7:59 AM, marco.ferrag...@gmail.com
 wrote:
> Hi all! I'm new to django and I'm experimenting with models but I have
> some trouble. I've minimized my problem to this code:
>
> class TestBase(models.Model):
>    base = models.CharField(max_length=255)
>
> from django.contrib import admin
> class TestA(TestBase):
>    testb = models.CharField(max_length=255)
>
> admin.site.register(TestA)
>
> class TestB(TestBase):
>    testc = models.CharField(max_length=255)
>
> admin.site.register(TestB)
>
> Trying to add TestA instances from admin interface I have this error:
> Cannot assign "''": "TestA.testb" must be a "TestB" instance.
>
> why testb should be a TestB instance?? It's a simple field!

I suspect this is because of something that is described in the MTI docs:

http://docs.djangoproject.com/en/1.2/topics/db/models/#multi-table-inheritance

Translated to you example the relevant paragraph says:

"If you have a TestBase that is also a TestB, you can get from the TestBase
object to the TestB object by using the lower-case version of the model name:

>>> p = TestBase.objects.get(id=12)
# If p is a TestB object, this will give the child class:
>>> p.testb


"

The TestA model is inheriting that 'testb' accesor from TestBase to TestB
and it is clashing with the identically named field.

-- 
Ramiro Morales

-- 
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: problems with model inheritance if base class is not abstract

2010-11-20 Thread Michael Sprayberry


--- On Sat, 11/20/10, marco.ferrag...@gmail.com <marco.ferrag...@gmail.com> 
wrote:


From: marco.ferrag...@gmail.com <marco.ferrag...@gmail.com>
Subject: problems with model inheritance if base class is not abstract
To: "Django users" <django-users@googlegroups.com>
Date: Saturday, November 20, 2010, 5:59 AM


Hi all! I'm new to django and I'm experimenting with models but I have
some trouble. I've minimized my problem to this code:

class TestBase(models.Model):
    base = models.CharField(max_length=255)

from django.contrib import admin
class TestA(TestBase):
    testb = models.CharField(max_length=255)

admin.site.register(TestA)

class TestB(TestBase):
    testc = models.CharField(max_length=255)

admin.site.register(TestB)

Trying to add TestA instances from admin interface I have this error:
Cannot assign "''": "TestA.testb" must be a "TestB" instance.

why testb should be a TestB instance?? It's a simple field!

If TestBase is declared as abstract using the internal Meta Class I no
more have the error. Is this a bug or there is something that I don't
understand?

Thanks in advance :)

I think your issue is in how you are registering
 
is should look like
 
admin.site.register(TestBase, TestA)
admin.site.register(TestBase, TestB)


  

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



problems with model inheritance if base class is not abstract

2010-11-20 Thread marco.ferrag...@gmail.com
Hi all! I'm new to django and I'm experimenting with models but I have
some trouble. I've minimized my problem to this code:

class TestBase(models.Model):
base = models.CharField(max_length=255)

from django.contrib import admin
class TestA(TestBase):
testb = models.CharField(max_length=255)

admin.site.register(TestA)

class TestB(TestBase):
testc = models.CharField(max_length=255)

admin.site.register(TestB)

Trying to add TestA instances from admin interface I have this error:
Cannot assign "''": "TestA.testb" must be a "TestB" instance.

why testb should be a TestB instance?? It's a simple field!

If TestBase is declared as abstract using the internal Meta Class I no
more have the error. Is this a bug or there is something that I don't
understand?

Thanks in advance :)

-- 
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: Model Inheritance.

2010-10-29 Thread Miguel Araujo
Hi Tom,

You might want to have a look at inheritanceCastModel from
django-model-utils by Carl Meyer
http://github.com/carljm/django-model-utils

Best regards,
Miguel Araujo

2010/10/29 David De La Harpe Golden 

> On 29/10/10 00:04, Tom Eastman wrote:
>
>  That's correct, but I want to take a 'Place' object, that doesn't have a
>> 'restaurant', and turn it *in to* a 'Restaurant' by adding the
>> corresponding row to the Restaurant table.
>>
>
>
> So you have a place.
>
> p = Place(name="3rd Circle of Hell")
> p.save()
>
> This should work:
>
> r = Restaurant(serves_hot_dogs=True)
> r.place_ptr = p
> r.save()
>
> If you then want an r that has picked up the now-should-be-inherited place
> attrs, you'll have to do something like:
>
> r = Restaurant.objects.get(pk=r.pk)
>
> print r.name
> 3rd Circle of Hell
>
>
>
> --
> 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.
>
>

-- 
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: Model Inheritance.

2010-10-29 Thread David De La Harpe Golden

On 29/10/10 00:04, Tom Eastman wrote:


That's correct, but I want to take a 'Place' object, that doesn't have a
'restaurant', and turn it *in to* a 'Restaurant' by adding the
corresponding row to the Restaurant table.



So you have a place.

p = Place(name="3rd Circle of Hell")
p.save()

This should work:

r = Restaurant(serves_hot_dogs=True)
r.place_ptr = p
r.save()

If you then want an r that has picked up the now-should-be-inherited 
place attrs, you'll have to do something like:


r = Restaurant.objects.get(pk=r.pk)

print r.name
3rd Circle of Hell


--
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: Model Inheritance.

2010-10-28 Thread Tom Eastman

On 29/10/10 11:06, Carles Barrobés wrote:

Your "place" object will contain an attribute called "restaurant" to
access
the object as an instance of the subclass.

If this place object is an instance of another place subclass,
accessing the
restaurant attribute will raise a DoesNotExist error.

Carles.


That's correct, but I want to take a 'Place' object, that doesn't have a 
'restaurant', and turn it *in to* a 'Restaurant' by adding the 
corresponding row to the Restaurant table.


--
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: Model Inheritance.

2010-10-28 Thread Carles Barrobés
Your "place" object will contain an attribute called "restaurant" to
access
the object as an instance of the subclass.

If this place object is an instance of another place subclass,
accessing the
restaurant attribute will raise a DoesNotExist error.

Carles.


On 28 Oct, 01:39, Tom Eastman <tom.east...@otago.ac.nz> wrote:
> I'm working with model inheritance, and I need to convert my objects
> into instances of its subclass.  Is there an easy way to do this?
>
> Looking at the example in:
>
> >http://docs.djangoproject.com/en/1.2/topics/db/models/#multi-table-in...
>
> I have a whole bunch of 'Place' objects that are in my database, and I
> want to turn them into 'Restaurant' objects.  How can I achieve this?
>
> (I want to end up with the implicit one-to-one relation in 'Restaurant'
> to be pointing to the already existing object in 'Place')
>
> Cheers!
>
>      Tom

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



Model Inheritance.

2010-10-27 Thread Tom Eastman
I'm working with model inheritance, and I need to convert my objects 
into instances of its subclass.  Is there an easy way to do this?



Looking at the example in:


http://docs.djangoproject.com/en/1.2/topics/db/models/#multi-table-inheritance


I have a whole bunch of 'Place' objects that are in my database, and I 
want to turn them into 'Restaurant' objects.  How can I achieve this?


(I want to end up with the implicit one-to-one relation in 'Restaurant' 
to be pointing to the already existing object in 'Place')


Cheers!

Tom

--
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: Bug in model inheritance?

2010-09-28 Thread phill
Alec,

Thanks.. yeah, your fix forces the fields to pk=True, which doesn't
redundantly serialize the field with it's custom name in my case. If
for some reason you wanted to ensure that the field was serialized
using it's custom field name though.. there doesn't appear to be a way
to do that. I'm pretty convinced this is a bug.

Phill

On Sep 28, 11:12 am, Alec Shaner  wrote:
> As to whether it's a bug or not I have no idea, though it seems so.
>
> If you use:
>
>     entity = models.OneToOneField(Entity, parent_link=True, primary_key=True)
>
> it will create the primary key in both Kid and Adult tables, which
> sounds like what you want?
>
>
>
> On Tue, Sep 28, 2010 at 1:06 PM, phill  wrote:
> > This looks quite a bit like a bug, but we may be off the reservation
> > in terms of how we're using the product. (Disclaimer: I'm relatively
> > new to Django, and extremely new to the codebase that I ran into this
> > on).
>
> > We've got a form of schema-inheritance going on in this project in
> > order to accomplish shared-id-space and the ability to relate models
> > to one of a number of different types. The way that we've broken it
> > out runs us into a strange inconsistency in Django that specifically
> > affects our ability to serialize the objects. Here's a simplified
> > version of what we're doing:
>
> > class Entity(models.Model):
> >    entityType = models.CharField(editable=False,max_length=50)
>
> >    def __init__(self, *args, **kwargs):
> >        super(Entity, self).__init__(*args, **kwargs)
> >        self.entityType = self.__class__.__name__
>
> >    def __unicode__(self):
> >        return 'Entity: %s %s' %(self.entityType, self.id)
>
> > class BasePerson(Entity):
>
> >    entity = models.OneToOneField(Entity, parent_link=True)
> >    name = models.CharField(max_length=50)
>
> >    class Meta:
> >        abstract = True
>
> > class Kid(BasePerson):
> >    school = models.CharField(max_length=50)
>
> > class Adult(BasePerson):
> >    job = models.CharField(max_length=50)
>
> > When I dump instances of these models out using the standard fixtures
> > serialization, instances of Kid will serialize the 'entity' field, but
> > instances of Adult won't. The reason is because Adult's entity field
> > is marked primaryKey=True. Kid's is not. There appears to be a caching
> > issue here, because if I swap the order that Kid and Adult are defined
> > in.. the error reverses (now Kid's field will be marked pk).
>
> > Is this a bug? If not, what's the reasoning behind this behavior? Is
> > there a better pattern for accomplishing this kind of inheritance?
>
> > Thanks in advance for your help.
>
> > Phill
>
> > --
> > 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 
> > athttp://groups.google.com/group/django-users?hl=en.

-- 
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: Bug in model inheritance?

2010-09-28 Thread Alec Shaner
As to whether it's a bug or not I have no idea, though it seems so.

If you use:

entity = models.OneToOneField(Entity, parent_link=True, primary_key=True)

it will create the primary key in both Kid and Adult tables, which
sounds like what you want?

On Tue, Sep 28, 2010 at 1:06 PM, phill  wrote:
> This looks quite a bit like a bug, but we may be off the reservation
> in terms of how we're using the product. (Disclaimer: I'm relatively
> new to Django, and extremely new to the codebase that I ran into this
> on).
>
> We've got a form of schema-inheritance going on in this project in
> order to accomplish shared-id-space and the ability to relate models
> to one of a number of different types. The way that we've broken it
> out runs us into a strange inconsistency in Django that specifically
> affects our ability to serialize the objects. Here's a simplified
> version of what we're doing:
>
> class Entity(models.Model):
>    entityType = models.CharField(editable=False,max_length=50)
>
>    def __init__(self, *args, **kwargs):
>        super(Entity, self).__init__(*args, **kwargs)
>        self.entityType = self.__class__.__name__
>
>    def __unicode__(self):
>        return 'Entity: %s %s' %(self.entityType, self.id)
>
> class BasePerson(Entity):
>
>    entity = models.OneToOneField(Entity, parent_link=True)
>    name = models.CharField(max_length=50)
>
>    class Meta:
>        abstract = True
>
> class Kid(BasePerson):
>    school = models.CharField(max_length=50)
>
> class Adult(BasePerson):
>    job = models.CharField(max_length=50)
>
>
>
> When I dump instances of these models out using the standard fixtures
> serialization, instances of Kid will serialize the 'entity' field, but
> instances of Adult won't. The reason is because Adult's entity field
> is marked primaryKey=True. Kid's is not. There appears to be a caching
> issue here, because if I swap the order that Kid and Adult are defined
> in.. the error reverses (now Kid's field will be marked pk).
>
> Is this a bug? If not, what's the reasoning behind this behavior? Is
> there a better pattern for accomplishing this kind of inheritance?
>
> Thanks in advance for your help.
>
> Phill
>
> --
> 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.
>
>

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



Bug in model inheritance?

2010-09-28 Thread phill
This looks quite a bit like a bug, but we may be off the reservation
in terms of how we're using the product. (Disclaimer: I'm relatively
new to Django, and extremely new to the codebase that I ran into this
on).

We've got a form of schema-inheritance going on in this project in
order to accomplish shared-id-space and the ability to relate models
to one of a number of different types. The way that we've broken it
out runs us into a strange inconsistency in Django that specifically
affects our ability to serialize the objects. Here's a simplified
version of what we're doing:

class Entity(models.Model):
entityType = models.CharField(editable=False,max_length=50)

def __init__(self, *args, **kwargs):
super(Entity, self).__init__(*args, **kwargs)
self.entityType = self.__class__.__name__

def __unicode__(self):
return 'Entity: %s %s' %(self.entityType, self.id)

class BasePerson(Entity):

entity = models.OneToOneField(Entity, parent_link=True)
name = models.CharField(max_length=50)

class Meta:
abstract = True

class Kid(BasePerson):
school = models.CharField(max_length=50)

class Adult(BasePerson):
job = models.CharField(max_length=50)



When I dump instances of these models out using the standard fixtures
serialization, instances of Kid will serialize the 'entity' field, but
instances of Adult won't. The reason is because Adult's entity field
is marked primaryKey=True. Kid's is not. There appears to be a caching
issue here, because if I swap the order that Kid and Adult are defined
in.. the error reverses (now Kid's field will be marked pk).

Is this a bug? If not, what's the reasoning behind this behavior? Is
there a better pattern for accomplishing this kind of inheritance?

Thanks in advance for your help.

Phill

-- 
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: Multi-table + Abstract Model Inheritance

2010-09-18 Thread ringemup

Well, on the surface this works.  I'm sure if anything unexpected
happens I'll be back.

On Sep 17, 8:34 am, ringemup  wrote:
> Sure, it's easy enough to find out if it works in a general sense --
> but I'm also concerned about running into subtle bugs down the road,
> and having to restructure my entire database as a result.
>
> On Sep 17, 4:15 am, bruno desthuilliers
>
>  wrote:
> > On 16 sep, 22:11, ringemup  wrote:
>
> > > Is it possible for a model to inherit from an abstract model, which in
> > > turn inherits from a non-abstract model?
>
> > I don't thinks so, but I may be wrong. Now nothing prevents you from
> > trying by yourself, it shouldn't take long to find out !-)
>
>

-- 
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: Multi-table + Abstract Model Inheritance

2010-09-17 Thread ringemup

Sure, it's easy enough to find out if it works in a general sense --
but I'm also concerned about running into subtle bugs down the road,
and having to restructure my entire database as a result.


On Sep 17, 4:15 am, bruno desthuilliers
 wrote:
> On 16 sep, 22:11, ringemup  wrote:
>
> > Is it possible for a model to inherit from an abstract model, which in
> > turn inherits from a non-abstract model?
>
> I don't thinks so, but I may be wrong. Now nothing prevents you from
> trying by yourself, it shouldn't take long to find out !-)

-- 
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: Multi-table + Abstract Model Inheritance

2010-09-17 Thread bruno desthuilliers
On 16 sep, 22:11, ringemup  wrote:
> Is it possible for a model to inherit from an abstract model, which in
> turn inherits from a non-abstract model?

I don't thinks so, but I may be wrong. Now nothing prevents you from
trying by yourself, it shouldn't take long to find out !-)

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



Multi-table + Abstract Model Inheritance

2010-09-16 Thread ringemup
Is it possible for a model to inherit from an abstract model, which in
turn inherits from a non-abstract model?

Here's an example.  In this case, the reason for using multi-table
inheritance rather than an explicit one-to-one relation would be that
the office addresses would be editable via office child model inlines
from the Business model's admin screen (i.e. not requiring the
currently-impossible nested inlines.)

Would this work, or blow up in my face (in subtle-or-not ways)?

class Address(models.Model):
  line_1 = models.Char_field(max_length=128)
  ...

class Business(models.Model):
  name = models.CharField(max_length=50)
  ...

class Office(Address):
  business = models.ForeignKey(Business, related_name='')
  phone = models.CharField(max_length=30)
  ...
  class Meta:
abstract = True

class DataCenter(Office):
  bandwidth = models.PositiveIntegerField()
  ...

class CorporateOffice(Office):
  office_manager = models.ForeignKey('Employee')
  ...

class Employee(models.Model):
  employer = models.ForeignKey(Business)
  home_address = models.ForeignKey(Address)

-- 
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: model inheritance, abtract=True

2010-08-05 Thread Roald de Vries

On Aug 5, 2010, at 3:15 PM, Roald de Vries wrote:

On Aug 5, 2010, at 3:00 PM, Emily Rodgers wrote:



On Aug 5, 1:50 pm, Roald de Vries  wrote:

Dear all,

I have the following error, and don't know what it means:

Error: One or more models did not validate:
update.personupdate: 'address' has a relation with model  
Address,

which has either not been installed or is abstract.

I did a pretty big refactoring, but I think the problems started  
when
I separated my Person class into an abstract base class  
PersonProfile
and a derived class Person, and added the class PersonUpdate,  
deriving

from PersonProfile too.

Can anybody help?

Thanks in advance, cheers,

Roald


Can you provide some code snippets from your model definitions?


I had adapted the error a little, but here the real code (in Dutch)  
and the corresponding errors. I can help you with the Dutch if it's  
necessary ;-).



#
# in core.models:
#

# ...
class Persoonprofiel(models.Model):
   geslacht   = models.CharField(max_length=8, choices=(('M',  
'Man'), ('V', 'Vrouw')))

   voorletters= models.CharField(max_length=12, blank=False)
   # ...
   class Meta:
   abstract = True
# ...
class Persoon(Persoonprofiel):
   foto   = models.ImageField(upload_to="personen_fotos",  
blank=True)

   titel  = models.CharField(max_length=100, blank=True)
   # ...
   class Meta:
   verbose_name = 'Persoon'
   verbose_name_plural = 'Personen'
   ordering = ['achternaam']


###
# in update.models:
###

# ...
class PersoonUpdate(Persoonprofiel):
   persoon  = models.ForeignKey('Persoon')
   bezoekadres  = models.ForeignKey('Adres',  
related_name='persoonupdates_als_bezoekadres',  blank=True, null=True)

   # ...


#
# errors:
#

Error: One or more models did not validate:
update.persoonupdate: 'persoon' has a relation with model Persoon,  
which has either not been installed or is abstract.
update.persoonupdate: 'bezoekadres' has a relation with model Adres,  
which has either not been installed or is abstract.

# ...


Solved. Solution: omit the quotes the referenced models that foreign  
keys refer to.


--
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: model inheritance, abtract=True

2010-08-05 Thread Roald de Vries

On Aug 5, 2010, at 3:00 PM, Emily Rodgers wrote:



On Aug 5, 1:50 pm, Roald de Vries  wrote:

Dear all,

I have the following error, and don't know what it means:

 Error: One or more models did not validate:
 update.personupdate: 'address' has a relation with model  
Address,

which has either not been installed or is abstract.

I did a pretty big refactoring, but I think the problems started when
I separated my Person class into an abstract base class PersonProfile
and a derived class Person, and added the class PersonUpdate,  
deriving

from PersonProfile too.

Can anybody help?

Thanks in advance, cheers,

Roald


Can you provide some code snippets from your model definitions?


I had adapted the error a little, but here the real code (in Dutch)  
and the corresponding errors. I can help you with the Dutch if it's  
necessary ;-).



#
# in core.models:
#

# ...
class Persoonprofiel(models.Model):
geslacht   = models.CharField(max_length=8, choices=(('M',  
'Man'), ('V', 'Vrouw')))

voorletters= models.CharField(max_length=12, blank=False)
# ...
class Meta:
abstract = True
# ...
class Persoon(Persoonprofiel):
foto   = models.ImageField(upload_to="personen_fotos",  
blank=True)

titel  = models.CharField(max_length=100, blank=True)
# ...
class Meta:
verbose_name = 'Persoon'
verbose_name_plural = 'Personen'
ordering = ['achternaam']


###
# in update.models:
###

# ...
class PersoonUpdate(Persoonprofiel):
persoon  = models.ForeignKey('Persoon')
bezoekadres  = models.ForeignKey('Adres',  
related_name='persoonupdates_als_bezoekadres',  blank=True, null=True)

# ...


#
# errors:
#

Error: One or more models did not validate:
update.persoonupdate: 'persoon' has a relation with model Persoon,  
which has either not been installed or is abstract.
update.persoonupdate: 'bezoekadres' has a relation with model Adres,  
which has either not been installed or is abstract.

# ...




--
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: model inheritance, abtract=True

2010-08-05 Thread Emily Rodgers


On Aug 5, 1:50 pm, Roald de Vries  wrote:
> Dear all,
>
> I have the following error, and don't know what it means:
>
>      Error: One or more models did not validate:
>      update.personupdate: 'address' has a relation with model Address,  
> which has either not been installed or is abstract.
>
> I did a pretty big refactoring, but I think the problems started when  
> I separated my Person class into an abstract base class PersonProfile  
> and a derived class Person, and added the class PersonUpdate, deriving  
> from PersonProfile too.
>
> Can anybody help?
>
> Thanks in advance, cheers,
>
> Roald

Can you provide some code snippets from your model definitions?

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



model inheritance, abtract=True

2010-08-05 Thread Roald de Vries

Dear all,

I have the following error, and don't know what it means:

Error: One or more models did not validate:
update.personupdate: 'address' has a relation with model Address,  
which has either not been installed or is abstract.


I did a pretty big refactoring, but I think the problems started when  
I separated my Person class into an abstract base class PersonProfile  
and a derived class Person, and added the class PersonUpdate, deriving  
from PersonProfile too.


Can anybody help?

Thanks in advance, cheers,

Roald

--
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: Model inheritance and simple access

2010-06-08 Thread Jason Beaudoin
sounds like magic, though django usually handles magic well :)


On Tue, Jun 8, 2010 at 7:18 PM, John M <retireonc...@gmail.com> wrote:
> I was hoping to avoid that type of code, but instead have put a field
> in the linked parent to indicate what type the child is and then have
> a method in the parent as a property which returns the correct child
> type.  Works for now, would be nice if the framework kept track of it,
> but it's a rare case.
>
> J
>
> On Jun 8, 12:41 pm, Dan Harris <dih0...@gmail.com> wrote:
>> Not sure if this will work as I don't usually do much with model
>> inheritance but according to docs 
>> at:http://docs.djangoproject.com/en/dev/topics/db/models/#id7
>> this might work (not pretty, but somewhat minimal code)...
>>
>> p = Parent1.objects.get(id=1)
>> try:
>>    p.childa.basemthod()
>> except:
>>    try:
>>       p.childb.basemethod()
>>    except:
>>       raise Execption("not ChildA or ChildB")
>>
>> Django adds in the lower cased name of the class as a property when
>> you query the super class and throws an exception if you access a
>> property that isn't there. So something like the above "might" work.
>> And obviously if you have like 5 child classes, this gets ugly very
>> quickly.
>>
>> Dan Harris
>> dih0...@gmail.com
>>
>> On Jun 8, 3:27 pm, John M <retireonc...@gmail.com> wrote:
>>
>> > Hmm, that doesn't really get me what I want, it just caches the
>> > related child objects in one SQL query.
>>
>> > What I want is a single interface and have django figure out what type
>> > of child object I have (like multiple inheritance but 'better').
>>
>> > So in my example:
>>
>> > p = Parent1.objects.get(id=1)
>> > p.child.basemethod()
>>
>> > django would know what p.child is (either ChildA or ChildB) and I
>> > wouldn't need to know.
>>
>> > Is that available?
>>
>> > J
>>
>> > On Jun 8, 11:09 am, Dejan Noveski <dr.m...@gmail.com> wrote:
>>
>> > >http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4
>>
>> > > select_related()
>>
>> > > On Tue, Jun 8, 2010 at 8:05 PM, John M <retireonc...@gmail.com> wrote:
>> > > > I've gotten model inheritance working just fine, but was hoping
>> > > > someone could confirm the best way to access the model.
>>
>> > > > When I have a Base model which has a ForeignKey to a parent table, and
>> > > > that base model has inherited models after it, how can I refer to only
>> > > > one name when referencing the parent model.
>>
>> > > > As an example:
>>
>> > > > class Base(models.Model):
>> > > >    parent = models.ForeignKey(Model1)
>>
>> > > >    class Meta:
>> > > >        abstract = True
>>
>> > > >    def basemethod():
>> > > >      print "hello"
>>
>> > > > class ChildA(Base):
>> > > >    pass
>>
>> > > > class ChildB(Base):
>> > > >    pass
>>
>> > > > p1 = Model1()
>> > > > p1.save
>> > > > x = ChildA()
>> > > > x.parent = P1
>> > > > x.save()
>>
>> > > > p2 = Model1()
>> > > > p2.save()
>> > > > y = ChildB()
>> > > > y.parent = P1
>> > > > y.save()
>>
>> > > > Now, I want to access the children from the parent, but I don't want
>> > > > to have to know what base class they are, is there a way to do that?
>> > > > Right now I'm using a property which figures it out based on some
>> > > > other fields, but would love to be able to say
>>
>> > > > p = Parent1.objects.get(id=1)
>> > > > p.child.basemethod()
>>
>> > > > Is this possible?
>>
>> > > > 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<django-users%2bunsubscr...@google
>> > > >  groups.com>
>> > > > .
>> > > > For more options, visit this group at
>> > > >http://groups.google.com/group/django-users?hl=en.
>>
>> > > --
>> > > --
>> > > Dejan Noveski
>> > > Web Developer
>> > > dr.m...@gmail.com
>> > > Twitter:http://twitter.com/dekomote|LinkedIn:http://mk.linkedin.com/in/dejannoveski
>
> --
> 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.
>
>

-- 
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: Model inheritance and simple access

2010-06-08 Thread John M
I was hoping to avoid that type of code, but instead have put a field
in the linked parent to indicate what type the child is and then have
a method in the parent as a property which returns the correct child
type.  Works for now, would be nice if the framework kept track of it,
but it's a rare case.

J

On Jun 8, 12:41 pm, Dan Harris <dih0...@gmail.com> wrote:
> Not sure if this will work as I don't usually do much with model
> inheritance but according to docs 
> at:http://docs.djangoproject.com/en/dev/topics/db/models/#id7
> this might work (not pretty, but somewhat minimal code)...
>
> p = Parent1.objects.get(id=1)
> try:
>    p.childa.basemthod()
> except:
>    try:
>       p.childb.basemethod()
>    except:
>       raise Execption("not ChildA or ChildB")
>
> Django adds in the lower cased name of the class as a property when
> you query the super class and throws an exception if you access a
> property that isn't there. So something like the above "might" work.
> And obviously if you have like 5 child classes, this gets ugly very
> quickly.
>
> Dan Harris
> dih0...@gmail.com
>
> On Jun 8, 3:27 pm, John M <retireonc...@gmail.com> wrote:
>
> > Hmm, that doesn't really get me what I want, it just caches the
> > related child objects in one SQL query.
>
> > What I want is a single interface and have django figure out what type
> > of child object I have (like multiple inheritance but 'better').
>
> > So in my example:
>
> > p = Parent1.objects.get(id=1)
> > p.child.basemethod()
>
> > django would know what p.child is (either ChildA or ChildB) and I
> > wouldn't need to know.
>
> > Is that available?
>
> > J
>
> > On Jun 8, 11:09 am, Dejan Noveski <dr.m...@gmail.com> wrote:
>
> > >http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4
>
> > > select_related()
>
> > > On Tue, Jun 8, 2010 at 8:05 PM, John M <retireonc...@gmail.com> wrote:
> > > > I've gotten model inheritance working just fine, but was hoping
> > > > someone could confirm the best way to access the model.
>
> > > > When I have a Base model which has a ForeignKey to a parent table, and
> > > > that base model has inherited models after it, how can I refer to only
> > > > one name when referencing the parent model.
>
> > > > As an example:
>
> > > > class Base(models.Model):
> > > >    parent = models.ForeignKey(Model1)
>
> > > >    class Meta:
> > > >        abstract = True
>
> > > >    def basemethod():
> > > >      print "hello"
>
> > > > class ChildA(Base):
> > > >    pass
>
> > > > class ChildB(Base):
> > > >    pass
>
> > > > p1 = Model1()
> > > > p1.save
> > > > x = ChildA()
> > > > x.parent = P1
> > > > x.save()
>
> > > > p2 = Model1()
> > > > p2.save()
> > > > y = ChildB()
> > > > y.parent = P1
> > > > y.save()
>
> > > > Now, I want to access the children from the parent, but I don't want
> > > > to have to know what base class they are, is there a way to do that?
> > > > Right now I'm using a property which figures it out based on some
> > > > other fields, but would love to be able to say
>
> > > > p = Parent1.objects.get(id=1)
> > > > p.child.basemethod()
>
> > > > Is this possible?
>
> > > > 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<django-users%2bunsubscr...@google
> > > >  groups.com>
> > > > .
> > > > For more options, visit this group at
> > > >http://groups.google.com/group/django-users?hl=en.
>
> > > --
> > > --
> > > Dejan Noveski
> > > Web Developer
> > > dr.m...@gmail.com
> > > Twitter:http://twitter.com/dekomote|LinkedIn:http://mk.linkedin.com/in/dejannoveski

-- 
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: Model inheritance and simple access

2010-06-08 Thread Dan Harris
Not sure if this will work as I don't usually do much with model
inheritance but according to docs at: 
http://docs.djangoproject.com/en/dev/topics/db/models/#id7
this might work (not pretty, but somewhat minimal code)...


p = Parent1.objects.get(id=1)
try:
   p.childa.basemthod()
except:
   try:
  p.childb.basemethod()
   except:
  raise Execption("not ChildA or ChildB")

Django adds in the lower cased name of the class as a property when
you query the super class and throws an exception if you access a
property that isn't there. So something like the above "might" work.
And obviously if you have like 5 child classes, this gets ugly very
quickly.

Dan Harris
dih0...@gmail.com


On Jun 8, 3:27 pm, John M <retireonc...@gmail.com> wrote:
> Hmm, that doesn't really get me what I want, it just caches the
> related child objects in one SQL query.
>
> What I want is a single interface and have django figure out what type
> of child object I have (like multiple inheritance but 'better').
>
> So in my example:
>
> p = Parent1.objects.get(id=1)
> p.child.basemethod()
>
> django would know what p.child is (either ChildA or ChildB) and I
> wouldn't need to know.
>
> Is that available?
>
> J
>
> On Jun 8, 11:09 am, Dejan Noveski <dr.m...@gmail.com> wrote:
>
>
>
> >http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4
>
> > select_related()
>
> > On Tue, Jun 8, 2010 at 8:05 PM, John M <retireonc...@gmail.com> wrote:
> > > I've gotten model inheritance working just fine, but was hoping
> > > someone could confirm the best way to access the model.
>
> > > When I have a Base model which has a ForeignKey to a parent table, and
> > > that base model has inherited models after it, how can I refer to only
> > > one name when referencing the parent model.
>
> > > As an example:
>
> > > class Base(models.Model):
> > >    parent = models.ForeignKey(Model1)
>
> > >    class Meta:
> > >        abstract = True
>
> > >    def basemethod():
> > >      print "hello"
>
> > > class ChildA(Base):
> > >    pass
>
> > > class ChildB(Base):
> > >    pass
>
> > > p1 = Model1()
> > > p1.save
> > > x = ChildA()
> > > x.parent = P1
> > > x.save()
>
> > > p2 = Model1()
> > > p2.save()
> > > y = ChildB()
> > > y.parent = P1
> > > y.save()
>
> > > Now, I want to access the children from the parent, but I don't want
> > > to have to know what base class they are, is there a way to do that?
> > > Right now I'm using a property which figures it out based on some
> > > other fields, but would love to be able to say
>
> > > p = Parent1.objects.get(id=1)
> > > p.child.basemethod()
>
> > > Is this possible?
>
> > > 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<django-users%2bunsubscr...@google
> > >  groups.com>
> > > .
> > > For more options, visit this group at
> > >http://groups.google.com/group/django-users?hl=en.
>
> > --
> > --
> > Dejan Noveski
> > Web Developer
> > dr.m...@gmail.com
> > Twitter:http://twitter.com/dekomote|LinkedIn:http://mk.linkedin.com/in/dejannoveski

-- 
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: Model inheritance and simple access

2010-06-08 Thread John M
Hmm, that doesn't really get me what I want, it just caches the
related child objects in one SQL query.

What I want is a single interface and have django figure out what type
of child object I have (like multiple inheritance but 'better').

So in my example:

p = Parent1.objects.get(id=1)
p.child.basemethod()

django would know what p.child is (either ChildA or ChildB) and I
wouldn't need to know.

Is that available?

J

On Jun 8, 11:09 am, Dejan Noveski <dr.m...@gmail.com> wrote:
> http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4
>
> select_related()
>
>
>
> On Tue, Jun 8, 2010 at 8:05 PM, John M <retireonc...@gmail.com> wrote:
> > I've gotten model inheritance working just fine, but was hoping
> > someone could confirm the best way to access the model.
>
> > When I have a Base model which has a ForeignKey to a parent table, and
> > that base model has inherited models after it, how can I refer to only
> > one name when referencing the parent model.
>
> > As an example:
>
> > class Base(models.Model):
> >    parent = models.ForeignKey(Model1)
>
> >    class Meta:
> >        abstract = True
>
> >    def basemethod():
> >      print "hello"
>
> > class ChildA(Base):
> >    pass
>
> > class ChildB(Base):
> >    pass
>
> > p1 = Model1()
> > p1.save
> > x = ChildA()
> > x.parent = P1
> > x.save()
>
> > p2 = Model1()
> > p2.save()
> > y = ChildB()
> > y.parent = P1
> > y.save()
>
> > Now, I want to access the children from the parent, but I don't want
> > to have to know what base class they are, is there a way to do that?
> > Right now I'm using a property which figures it out based on some
> > other fields, but would love to be able to say
>
> > p = Parent1.objects.get(id=1)
> > p.child.basemethod()
>
> > Is this possible?
>
> > 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<django-users%2bunsubscr...@googlegroups.com>
> > .
> > For more options, visit this group at
> >http://groups.google.com/group/django-users?hl=en.
>
> --
> --
> Dejan Noveski
> Web Developer
> dr.m...@gmail.com
> Twitter:http://twitter.com/dekomote| 
> LinkedIn:http://mk.linkedin.com/in/dejannoveski

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



Model inheritance and simple access

2010-06-08 Thread John M
I've gotten model inheritance working just fine, but was hoping
someone could confirm the best way to access the model.

When I have a Base model which has a ForeignKey to a parent table, and
that base model has inherited models after it, how can I refer to only
one name when referencing the parent model.

As an example:

class Base(models.Model):
parent = models.ForeignKey(Model1)

class Meta:
abstract = True

def basemethod():
  print "hello"

class ChildA(Base):
pass

class ChildB(Base):
pass

p1 = Model1()
p1.save
x = ChildA()
x.parent = P1
x.save()

p2 = Model1()
p2.save()
y = ChildB()
y.parent = P1
y.save()

Now, I want to access the children from the parent, but I don't want
to have to know what base class they are, is there a way to do that?
Right now I'm using a property which figures it out based on some
other fields, but would love to be able to say

p = Parent1.objects.get(id=1)
p.child.basemethod()

Is this possible?

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



Re: Model inheritance foreign key user

2010-04-04 Thread Thierry Chich
You are right but it would not change his problem. If 2 or more  
classes inherit from a class with a foreignkey or a manytomany, there  
will be a conflict in the related name




Le 4 avr. 2010 à 14:11, Daniel Roseman  a  
écrit :



On Apr 3, 10:37 pm, Fredrik  wrote:

What I want is to "automatic" add an owner to every object..

Is there another way to accomplish the same?

Fredrik



Do you need the PersistentModel field to exist in a separate table? It
sounds to me as if that would be better off as an abstract 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-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 
.




--
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: Model inheritance foreign key user

2010-04-04 Thread Daniel Roseman
On Apr 3, 10:37 pm, Fredrik  wrote:
> What I want is to "automatic" add an owner to every object..
>
> Is there another way to accomplish the same?
>
> Fredrik
>

Do you need the PersistentModel field to exist in a separate table? It
sounds to me as if that would be better off as an abstract 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-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: Model inheritance foreign key user

2010-04-04 Thread Thierry Chich





Le 3 avr. 2010 à 23:37, Fredrik  a écrit :


What I want is to "automatic" add an owner to every object..

Is there another way to accomplish the same?


I see. I have had a similar problem. I have tried a similar solution  
with exactly the same effect.
 I could have add manualy a foreignkey to each class with a proper  
related_name. At this point, i realised that it will be an huge load  
for the database and I have simplified my authorization design. I have  
deeply look to an app called 'namespace' but it don't fit to my need  
(but perhaps it could fit yours ?).
Now it work with a simple authorization function applied on the  
queryset when i populate my forms.


Thierry


Fredrik


On Apr 3, 10:48 pm, Thierry Chich  wrote:

I think that if you want make inheritance it is because you want to
have others subclasses. But then, your related name will be same for
all the subclasses.
There is no solution with the stable version. In the dev version, it
is possible to add the origin class name in the related_name. It is
documented, but i don't remember where exactly.

Thierry

Le 3 avr. 2010 à 20:38, Fredrik  a écrit :


Hi,
I want to use it like this:



"""
class PersistentModel(models.Model):
   deleted = models.BooleanField(default = False)
   date_created = models.DateTimeField(default=datetime.now)
   date_edited = models.DateTimeField(default=datetime.now)
   owner = models.ForeignKey(User)



class Contacts(PersistentModel):
   full_name = models.CharField("Fullt navn", max_length=20)
   address = models.CharField("Adresse", max_length=50)
   phone = models.CharField("Telefon", max_length=20)
   email = models.EmailField("Epost", max_length=50)



   def __unicode__ (self):
   return self.full_name
"""



But it creates errors,
" Reverse query name for field 'owner' clashes with field
'User.email'. Add a related_name argument to the definition for
'owner'.


But if I try to add related_name to owner, then I get a lot of  
errors

like this:



"""
contacts.contacts: Accessor for field 'owner' clashes with related
field 'User.Owner'. Add a related_name argument to the definition  
for

'owner'.
contacts.contacts: Reverse query name for field 'owner' clashes with
related field 'User.Owner'. Add a related_name argument to the
definition for 'owner'.
contacts.contacts: Accessor for field 'owner' clashes with related
field 'User.Owner'. Add a related_name argument to the definition  
for

'owner'.
contacts.contacts: Reverse query name for field 'owner' clashes with
related field 'User.Owner'. Add a related_name argument to the
definition for 'owner'.
contacts.contacts: Accessor for field 'owner' clashes with related
field 'User.Owner'. Add a related_name argument to the definition  
for

'owner'.
contacts.contacts: Reverse query name for field 'owner' clashes with
related field 'User.Owner'. Add a related_name argument to the
definition for 'owner'.
contacts.contacts: Accessor for field 'owner' clashes with related
field 'User.Owner'. Add a related_name argument to the definition  
for

'owner'.
"""



Hopefully, someone can help me out :)



--
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 athttp://groups.google.com/ 
group/django-users?hl=en

.


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




--
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: Model inheritance foreign key user

2010-04-03 Thread Fredrik
What I want is to "automatic" add an owner to every object..

Is there another way to accomplish the same?


Fredrik


On Apr 3, 10:48 pm, Thierry Chich  wrote:
> I think that if you want make inheritance it is because you want to  
> have others subclasses. But then, your related name will be same for  
> all the subclasses.
> There is no solution with the stable version. In the dev version, it  
> is possible to add the origin class name in the related_name. It is  
> documented, but i don't remember where exactly.
>
> Thierry
>
> Le 3 avr. 2010 à 20:38, Fredrik  a écrit :
>
> > Hi,
> > I want to use it like this:
>
> > """
> > class PersistentModel(models.Model):
> >    deleted = models.BooleanField(default = False)
> >    date_created = models.DateTimeField(default=datetime.now)
> >    date_edited = models.DateTimeField(default=datetime.now)
> >    owner = models.ForeignKey(User)
>
> > class Contacts(PersistentModel):
> >        full_name = models.CharField("Fullt navn", max_length=20)
> >        address = models.CharField("Adresse", max_length=50)
> >        phone = models.CharField("Telefon", max_length=20)
> >        email = models.EmailField("Epost", max_length=50)
>
> >        def __unicode__ (self):
> >            return self.full_name
> > """
>
> > But it creates errors,
> > " Reverse query name for field 'owner' clashes with field
> > 'User.email'. Add a related_name argument to the definition for
> > 'owner'.
>
> > But if I try to add related_name to owner, then I get a lot of errors
> > like this:
>
> > """
> > contacts.contacts: Accessor for field 'owner' clashes with related
> > field 'User.Owner'. Add a related_name argument to the definition for
> > 'owner'.
> > contacts.contacts: Reverse query name for field 'owner' clashes with
> > related field 'User.Owner'. Add a related_name argument to the
> > definition for 'owner'.
> > contacts.contacts: Accessor for field 'owner' clashes with related
> > field 'User.Owner'. Add a related_name argument to the definition for
> > 'owner'.
> > contacts.contacts: Reverse query name for field 'owner' clashes with
> > related field 'User.Owner'. Add a related_name argument to the
> > definition for 'owner'.
> > contacts.contacts: Accessor for field 'owner' clashes with related
> > field 'User.Owner'. Add a related_name argument to the definition for
> > 'owner'.
> > contacts.contacts: Reverse query name for field 'owner' clashes with
> > related field 'User.Owner'. Add a related_name argument to the
> > definition for 'owner'.
> > contacts.contacts: Accessor for field 'owner' clashes with related
> > field 'User.Owner'. Add a related_name argument to the definition for
> > 'owner'.
> > """
>
> > Hopefully, someone can help me out :)
>
> > --
> > 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 
> > athttp://groups.google.com/group/django-users?hl=en
> > .

-- 
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: Model inheritance foreign key user

2010-04-03 Thread Thierry Chich
I think that if you want make inheritance it is because you want to  
have others subclasses. But then, your related name will be same for  
all the subclasses.
There is no solution with the stable version. In the dev version, it  
is possible to add the origin class name in the related_name. It is  
documented, but i don't remember where exactly.


Thierry



Le 3 avr. 2010 à 20:38, Fredrik  a écrit :


Hi,
I want to use it like this:

"""
class PersistentModel(models.Model):
   deleted = models.BooleanField(default = False)
   date_created = models.DateTimeField(default=datetime.now)
   date_edited = models.DateTimeField(default=datetime.now)
   owner = models.ForeignKey(User)

class Contacts(PersistentModel):
   full_name = models.CharField("Fullt navn", max_length=20)
   address = models.CharField("Adresse", max_length=50)
   phone = models.CharField("Telefon", max_length=20)
   email = models.EmailField("Epost", max_length=50)

   def __unicode__ (self):
   return self.full_name
"""

But it creates errors,
" Reverse query name for field 'owner' clashes with field
'User.email'. Add a related_name argument to the definition for
'owner'.

But if I try to add related_name to owner, then I get a lot of errors
like this:

"""
contacts.contacts: Accessor for field 'owner' clashes with related
field 'User.Owner'. Add a related_name argument to the definition for
'owner'.
contacts.contacts: Reverse query name for field 'owner' clashes with
related field 'User.Owner'. Add a related_name argument to the
definition for 'owner'.
contacts.contacts: Accessor for field 'owner' clashes with related
field 'User.Owner'. Add a related_name argument to the definition for
'owner'.
contacts.contacts: Reverse query name for field 'owner' clashes with
related field 'User.Owner'. Add a related_name argument to the
definition for 'owner'.
contacts.contacts: Accessor for field 'owner' clashes with related
field 'User.Owner'. Add a related_name argument to the definition for
'owner'.
contacts.contacts: Reverse query name for field 'owner' clashes with
related field 'User.Owner'. Add a related_name argument to the
definition for 'owner'.
contacts.contacts: Accessor for field 'owner' clashes with related
field 'User.Owner'. Add a related_name argument to the definition for
'owner'.
"""



Hopefully, someone can help me out :)



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




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



Model inheritance foreign key user

2010-04-03 Thread Fredrik
Hi,
I want to use it like this:

"""
class PersistentModel(models.Model):
deleted = models.BooleanField(default = False)
date_created = models.DateTimeField(default=datetime.now)
date_edited = models.DateTimeField(default=datetime.now)
owner = models.ForeignKey(User)

class Contacts(PersistentModel):
full_name = models.CharField("Fullt navn", max_length=20)
address = models.CharField("Adresse", max_length=50)
phone = models.CharField("Telefon", max_length=20)
email = models.EmailField("Epost", max_length=50)

def __unicode__ (self):
return self.full_name
"""

But it creates errors,
" Reverse query name for field 'owner' clashes with field
'User.email'. Add a related_name argument to the definition for
'owner'.

But if I try to add related_name to owner, then I get a lot of errors
like this:

"""
contacts.contacts: Accessor for field 'owner' clashes with related
field 'User.Owner'. Add a related_name argument to the definition for
'owner'.
contacts.contacts: Reverse query name for field 'owner' clashes with
related field 'User.Owner'. Add a related_name argument to the
definition for 'owner'.
contacts.contacts: Accessor for field 'owner' clashes with related
field 'User.Owner'. Add a related_name argument to the definition for
'owner'.
contacts.contacts: Reverse query name for field 'owner' clashes with
related field 'User.Owner'. Add a related_name argument to the
definition for 'owner'.
contacts.contacts: Accessor for field 'owner' clashes with related
field 'User.Owner'. Add a related_name argument to the definition for
'owner'.
contacts.contacts: Reverse query name for field 'owner' clashes with
related field 'User.Owner'. Add a related_name argument to the
definition for 'owner'.
contacts.contacts: Accessor for field 'owner' clashes with related
field 'User.Owner'. Add a related_name argument to the definition for
'owner'.
"""



Hopefully, someone can help me out :)



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



Strange behaviour with select_related and model inheritance

2010-03-19 Thread Mark L.
Hello,

Here is an extremely simple scenario:

class Base(models.Model):
f1 = models.CharField(max_length=64)

class A(Base):
f2 = models.CharField(max_length=64)

class B(models.Model):
f3 = models.CharField(max_length=64)
b = models.OneToOneField('A', null=False, related_name="b_obj")

If you then try and do "print A.objects.select_related('b_obj').query'
it produces
Traceback (most recent call last):
  File "", line 1, in 
  File "django\db\models\sql\query.py", line 147, in __str__
sql, params = self.get_compiler(DEFAULT_DB_ALIAS).as_sql()
  File "django\db\models\sql\compiler.py", line 59, in as_sql
self.pre_sql_setup()
  File "django\db\models\sql\compiler.py", line 33, in pre_sql_setup
self.fill_related_selections()
  File "django\db\models\sql\compiler.py", line 616, in
fill_related_selections
chain = opts.get_base_chain(f.rel.to)
  File "django\db\models\options.py", line 440, in get_base_chain
% model._meta.module_name)
TypeError: 'a' is not an ancestor of this model

Incidentally, if I try to actually evaluate the queryset it turns out,
that no queries are run at all. Is it supposed to be like that?
In plain SQL this would be an inner join from A to Base followed by a
left outer join with B. Is it possible to make it work at all?

If you don't derive A from Base, it works perfectly (creates a left
outer join from A to B).

I hope, this makes sense

Mark

-- 
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: Model Inheritance - best practice for templates?

2010-02-24 Thread fgasperino

mis-clicked, continuing:


@register.filter
def A_get_B(instance):
    if isinstance(instance, B):
        return instance.b

    try:
        return instance.b
    except B.DoesNotExist:
        return None

and lastly, the template:

{% with a|A_get_B as b %}
{% if b %}
  .. work with b
{% endif %}
{% endwith %}

Any else have opinions on this? Barring content types, is this the
preferred method?

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



Model Inheritance - best practice for templates?

2010-02-24 Thread fgasperino
All,

Currently I'm working with the following 2 models:

class A (models.Model):
  ...
class B (A):
  somefield = ...

I have a generic views with querysets defined as:

url(r"A/view/(?P\d+)/$",
"django.views.generic.list_detail.object_detail", dict(queryset =
A.objects.all(), template_name = "views/view-A.template",
template_object_name = "A"), name = "view_A"),

url(r"A/list/$", "django.views.generic.list_detail.object_list",
dict(queryset = A.objects.all(), template_name = "lists/list-
As.template", template_object_name = "A", paginate_by = 20), name =
"list_As"),

I have a pair of templates that view individual, and list, A objects.
Should a B object be in the queryset results, I'm rendering additional
template content (B.somefield).

Currently, I'm accomplishing this with a template tag:

@register.filter
def A_get_B(instance):
if isinstance(instance, B):
return instance.b

try:

return event.userevent.user
except UserEvent.DoesNotExist:
return None

-- 
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: Model inheritance

2010-01-13 Thread Tomasz Zieliński
On 12 Sty, 20:52, a b  wrote:
> Hi,
>
> I have three models:
> Product
> SimpleProduct that extends Product
> GroupProduct that extends Product and have ManyToMany relation with
> SimpleProduct
>
> The reason to use the base Product model is so I can use paging.
> Is it possible to make a query that gives a list of GroupProducts and
> SimpleProducts that are not included in a GroupProduct.
> I don't want to show the same product twice, once standalone and once as
> part of a GroupProduct.
>
> I can add a field to SimpleProduct that indicates weather it's standalone or
> not and maybe update it using signals
> but it doesn't feel like the right way.
>

Quick, untried, ideas:

1. You could try using aggregation:

from django.db.models import Count
SimpleProduct.objects.annotate(belongs_to_groupproducts=Count
('groupproduct')).filter(belongs_to_groupproducts=0)

2. If this is "normal" inheritance (i.e. not an abstract one), then
SimpleProduct and GroupProduct have
implicit OneToOneField connecting them to Product. It means that you
probably could just filter Product-s and then downcast it.

--
Tomasz Zielinski
http://pyconsultant.eu
-- 
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.




Model inheritance

2010-01-12 Thread a b
Hi,

I have three models:
Product
SimpleProduct that extends Product
GroupProduct that extends Product and have ManyToMany relation with
SimpleProduct

The reason to use the base Product model is so I can use paging.
Is it possible to make a query that gives a list of GroupProducts and
SimpleProducts that are not included in a GroupProduct.
I don't want to show the same product twice, once standalone and once as
part of a GroupProduct.

I can add a field to SimpleProduct that indicates weather it's standalone or
not and maybe update it using signals
but it doesn't feel like the right way.

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



Re: Model inheritance - filtering base model only

2009-11-23 Thread esatterwh...@wi.rr.com
a simple solution would be to put pass the contentype id and object id
around in your url scheme

domain.com/ct_id-object_id/

from there you can get the content type, which will be able to tell
you the model, type, and give you the object.

type = ContentType.objects.get(pk=ct_id)
model = type.model_class()
obj = model.objects.get(pk=obj_id)

this would also cut down on the number of view functions you need to
write. It's a mini generic view for you app, just figure out a naming
convention for templates based on the model you have :

template = template_name or "appfolder/%s_detail.html" % type.model

you can have 1 url handle just about anything

Done and Done

On Nov 22, 6:32 pm, lfrodrigues  wrote:
> Hello,
>
> I have these models:
>
> class Player(models.Model):
>     .
>
> class PlayerM(Player):
>     ...
>
> If I do PlayerM.objects.all() e get all PlayerM objects and for
> Player.objects.all() I get all Player and PlayerM as expected.
>
> How can get only the objects of type Player (only retrieve the objects
> that were created with Player() constructor)?
>
> Regards,
>
> Luis

--

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: Model inheritance - filtering base model only

2009-11-23 Thread Doug Blank
On Mon, Nov 23, 2009 at 9:09 AM, lfrodrigues  wrote:
> I guess this solution works but for +50 the performance should be
> terrible...
>
> Shouldn't django have some option for this?

Could you set a field's value which is true for one, and false for the
other? Otherwise, could you just have two tables?

I wonder if ContentType could help?

obj_type = ContentType.objects.get_for_model(player)
source_refs = PlayerM.filter(object_type=obj_type)

(object_type gets created with generic relations)

-Doug

> On 23 Nov, 04:53, Preston Holmes  wrote:
>> Perhaps there is a more efficient way, but in my quick test, one can't
>> filter() a queryset based on __class__ of the model, but seems one can
>> manually filter it afterwords:
>>
>> qs = Player.objects.all()
>> for i,obj in enumerate(qs):
>>     if obj.__class__ != Player:
>>         del(qs[i])
>>
>> On Nov 22, 4:32 pm, lfrodrigues  wrote:
>>
>> > Hello,
>>
>> > I have these models:
>>
>> > class Player(models.Model):
>> >     .
>>
>> > class PlayerM(Player):
>> >     ...
>>
>> > If I do PlayerM.objects.all() e get all PlayerM objects and for
>> > Player.objects.all() I get all Player and PlayerM as expected.
>>
>> > How can get only the objects of type Player (only retrieve the objects
>> > that were created with Player() constructor)?
>>
>> > Regards,
>>
>> > Luis
>
> --
>
> 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=.
>
>
>

--

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




  1   2   3   >