Model set fields in Django - python

I have a Django model that needs to represent a set of data. What is the canonical way to implement this? I don't see a models.SetField() in the documentation. I could use a text field and pickling.
I recognize that this isn't the fastest way to do it, but this part of the code doesn't need to be super fast - simplicity is better at this point.

I'm not exactly sure what you are trying to achieve, but it seems to me your looking for some getter/setter functionality that automatically pickles the values:
import cPickle
class MyModel(models.Model):
cpickled_values = models.TextField()
def get_values(self):
return cPickle.loads(str(self.cpickled_values))
def set_values(self, value):
self.cpickled_value = cPickle.dumps(values)
values = property(get_values, set_values)
You can then do something like obj.values = {'item1': data1} and your data will be pickeld automatically.

Related

Django save object in database

First of all I should mention that I'm new to Python as well as Django.
I have a Django project with an sqlite3 database.
I have created a couple of classes for calculating some physical problems, and I want to access the result of these through my website using forms. My previous approach to this was to change my classes to functions, and create several model fields for my objects.
Then I reached a point where the output of my function was a 2D-array, which I have issues saving in my model. So I decided it would be easier just to store the entire object in the database - then I wouldn't have to change my classes to functions in order to utilize it in Django.
I'm using inputs for my calculations in a form, a and b below.
Is it possible to store objects in my model?
I have made a hypothetic example, not sure if the code works but hope that you get the point.
class Butterfly_model(models.Model):
a = models.FloatField(verbose_name='a')
b = models.FloatField(verbose_name='b')
results = >>>Some_Object_Field<<<
my computation script could contain something like this:
class Compute:
def __init__(self, a, b):
self.X=[]
self.Y=[]
for i in range(0,a):
self.X.append(i)
self.Y.append(i+b)
And my view.py contains following:
if form_input.is_valid():
instance = form_input.save(commit=False)
instance.results = Compute(instance.a,instance.b)
instance.save()
If not possible, does any of you have a suggestion for how handle calculations and resulting data like this?
Best regards,
Joachim
What you are probably looking for are model properties. From anticipating your needs I think you are looking for:
You can add properties to you models that calculate a function. For your case it would be sth like:
class Butterfly_model(models.Model):
a = models.FloatField(verbose_name='a')
b = models.FloatField(verbose_name='b')
#property
def X(self):
return [i for i in range(0,self.a)]
#property
def Y(self):
return [i+b for i in range(0,self.a)]
That way you can access X and Y for each model instance and do not need to save it in the database (if that is what you want?).

Django models - is there a reasonable solution for handling sub dicts as a field in Django models

I'm fairly new into Django and the Django orm. I need to model something like:
or in python psuedo code:
class Settings(Model):
subsettings1 = somekindofdictfield({key:fields.BooleanField(), key:fields.BooleanField()})
subsettings2 = somekindofdictfield({key:fields.BooleanField(), key:fields.BooleanField()})
I'm trying to avoide having to have seperate class for each kind of of subsettings. Which can be dynamic. So this solution look wrong:
class Settings(Model):
subsettings1 = ForeignKey(SubSettings1)
#etc
I'm not afraid of having many models (I already have) but I don't want unnecessary ones. with mode tables etc..
I'll be glad for ideas from exprienced Django developers.
Thanks!
If the settings are meant to be opaque (for example, you don't need to filter based on particular values in your dicts) you can just store these as regular Python objects using something like django-picklefield.
>>> from picklefield.fields import PickledObjectField
... class SomeObject(models.Model):
... args = PickledObjectField()
>>> obj = SomeObject()
>>> obj.args = ['fancy', {'objects': 'inside'}]
>>> obj.save()

Best practice for accessing distantly related Django models

Let say we have a long chain of Django models, where each references the one above through a ForeignKey field:
class One(models.Model):
# fields
class Two(models.Model):
one = models.ForeignKey(One)
...
class Ten(models.Model):
nine = models.ForeignKey(Nine)
Good! Now image, if you will, having an instance of the Ten model and wanting to grab the related One instance. This can result in long lines of attribute chaining like this:
ten_instance.nine.eight.seven.six.five.four.three.two.one
I'm wondering what the standard approach would be to this niggling issue. Do we leave it as is, being inherently descriptive and readable. Or do we aim to shorten such a line to make things more simple:
ten_instance.one
 But What's The Best Practice Here? Or is there a more simple solution?
Use Properties
My current approach would be to add a property to the Ten model, abstracting away that attribute chaining:
class Ten(models.Model):
nine = models.ForeignKey(Nine)
#property
def one(self):
return self.nine.eight.seven.six.five.four.three.two.one
I can see a downside to this tactic however, and that's the added mysticism involved. Does the Ten instance actually have a relation to the One model or not? I wouldn't be able to tell without inspecting the model myself.
You probably want to use django-mptt for sophisticated hierarchal models although it can be a bit ott. If you want a simple hierarchy then add a ForeignKey to self:
class Number(models.Model):
parent = models.ForeignKey('self', blank=True, null=True,
related_name='child')
then the query would be something like this based on a unique field, say slug:
Number.objects.get(parent__slug='one')

Django models and Python properties

I've tried to set up a Django model with a python property, like so:
class Post(models.Model):
_summary = models.TextField(blank=True)
body = models.TextField()
#property
def summary(self):
if self._summary:
return self._summary
else:
return self.body
#summary.setter
def summary(self, value):
self._summary = value
#summary.deleter
def summary(self):
self._summary = ''
So far so good, and in the console I can interact with the summary property just fine. But when I try to do anything Django-y with this, like Post(title="foo", summary="bar"), it throws a fit. Is there any way to get Django to play nice with Python properties?
Unfortunately, Django models don't play very nice with Python properties. The way it works, the ORM only recognizes the names of field instances in QuerySet filters.
You won't be able to refer to summary in your filters, instead you'll have to use _summary. This gets messy real quick, for example to refer to this field in a multi-table query, you'd have to use something like
User.objects.filter(post___summary__contains="some string")
See https://code.djangoproject.com/ticket/3148 for more detail on property support.

quick question: clear an attribute of a model in django

i think this is a pretty easy question for you.
I want to clear an attribute of a django-model.
If i have something like this:
class Book(models.Model):
name = models.TextField()
pages = models.IntegerField()
img = models.ImageField()
In an abstract function i want to clear an attribute, but at that time i don't know what type the field has. So examples would be name="", pages=0 or img=None.. Is there a way to do it in a generic way? I search something like SET_TO_EMPTY(book,"pages")
Do you know a function like that?
many thanks in advance!
I don't think there is a clean way of doing it. However, assuming you've set a default value (which you don't have) you can do it like this:
book.img = book._meta.get_field('img').default
Do note that your current model won't allow a None value. To allow those you have to set null=True and blank=True. For pages you need a default=0.

Categories