Wednesday, June 10, 2015

Re: How to DRY, define a set of model-fields and reuse them as multiple instances

El 10/06/15 12:33, ThomasTheDjangoFan escribió:
Hi Bruno,

Abstract Base Models come close but they don't allow me to combine multiple instances of the BaseModel in the DataHolderModel.

My goal is to store them all in one table without having to manually add all the fields.

Any suggestions?


Am Mittwoch, 10. Juni 2015 17:49:13 UTC+2 schrieb Bruno A.:
It looks like you want a Model to inherit from multiple base model? Multiple time from the same one, with different parameters?

I'm not sure I understood what you are trying to do, but maybe abstract models can help you?
https://docs.djangoproject.com/en/1.8/topics/db/models/#abstract-base-classes


On Tuesday, 9 June 2015 22:20:19 UTC+1, ThomasTheDjangoFan wrote:
Hi guys,

now this is kind of hard for me to explain, I hope that somebody understands what I actually want.

I am a python newbie and wonder if there is an easy solution.

They say: DRY!!

My question is:
How do a define an (abstract?) class including methods and fields
and then attach it to a real mode with variants instants?


The data needs to be available as realy models.* types, so I can use it in forms.


Hopefully this example makes it clear:


# I would love to keep it DRY and wonder if there is a solution for this in python?

# NOW THIS IS TOTALLY MADE UP
# Basically I would like to be able to define a definition of model-fields and functions
# and then be able to "attach" it to a model as various instances
class KidType (models.Model):
    NAMEHOLDER
= '' #nameholder

    NAMEHOLDER_text
= models.TextField()
    NAMEHOLDER_timestamp_updated
= models.DateTimeField(auto_now_add=False, auto_now=True)

   
def example_function_shared_among_types():
       
return str(self.NAMEHOLDER_text + self.NAMEHOLDER_timestamp_updated)

   
def set_NAMEHOLDER_text(value):
       
self.set_NAMEHOLDER_text(value)

#
class DataHolderModel(models.Model):
   
# Attach the above definition with different names
   
# and make them accessable
   
@attach (KidType, KidType.NAME = 'dataset1')
   
@attach (KidType, KidType.NAME = 'dataset2')
   
@attach (KidType, KidType.NAME = 'dataset3')

# Access the instances within the HolderModel:
data_holder
= DataHolderModel()
data_holder
.dataset1_text = 'value1'
data_holder
.set_dataset1_text('value1')
data_holder
.dataset2_text = 'value2'
data_holder
.dataset3_text = 'value3'

Any ideas? Can I do something like this?

I am really thankful for your tips
Thomas



If its the same data and maybe with different behaviour then proxy models could be what you want.


No comments:

Post a Comment