Given a pyscipopt.Model and its Solution, how to pass it to another model as a primal heuristic?
I'm currently writing the solution to a file via writeSol(), and then calling readSolFile() and addSol(). There should probably be a cleaner way.
This depends a bit on the structure of your two models. If they have the same variables in the same order (which is likely from what you wrote), then you can simply create a new solution in your model and copy all the values, ie:
variables = othermodel.getVars()
newvariables = model.getVars()
nvars = othermodel.getNVars()
newsol = self.model.createSol(self)
for i in range(nvars):
newsol[newvariables[i]] = othermodel.getSolVal(oldsol, variables[i])
self.model.trySol(newsol)
Let me know if this work/ doens't work
Related
I want a capability to update-and-read an object atomically. For example, something like a first() on top of update() below:
obj = MyModel.objects.filter(pk=100).update(counter=F('counter') + 1).first()
I know it is awkward construct. But just want to show my need.
For the record I have used class method like:
#classmethod
def update_counter(cls, job_id):
with transaction.atomic():
job = (cls.objects.select_for_update().get(pk=job_id))
job.counter += 1
job.save()
return job
where I would call as below and get my updated obj.
my_obj = my_obj.update_counter()
But the question is, is there any other django model technique given such read back are common and likely used by multiple threads to conclude something based on, say, the final count.
Digging deeper I could not find any direct way of getting the object(s) that I am updating in an sql chained way. As Dani Herrera commented above the update and read have to be two sql queries. Only mechanism that helps me with that requirement is therefore the class method I had also included above. In fact, it helps me to add additional field updates in the same class method atomically in future.
For example, the method could very well be "def update_progress(job_id, final_desired_count)" where I can update more fields such as "self.progress_percentage = (self.counter / final_desired_count) * 100".
The class method approach may turn out to be a good investment for me.
Suppose that you're creating a blog and each blogpost consists of an array of interleaving text fragments and fragments of svg (for instance).
You store each of those fragments in a custom django field (e.g. HTMLField and SVGField).
What's the best way to organize this?
How to maintain the order of fragments? This solution looks ugly:
class Post(models.Model):
title = CharField(1000)
class Fragment(models.Model):
index = IntegerField()
html = HTMLField()
svg = SVGField()
post = ForeignKey(Post)
As discussed, a separate model is a feasible way to go to record all the fragments. We use one IntegerField to record the fragment order, so that later one the whole Post could be recovered.
Some caveats here:
Use order_by, latest or slice n dice operations to sort/find elements.
When insert/delete operations are needed, it's going to break the overall sequence. We need to increase/decrease multiple elements to maintain the order. Use queryset and F() expression to change multiple records at once, like described in another SO post here.
There are some imperfections about the approach, but It's the best solution I could come up so far(I encountered similar situation before). Linked list is a good way but it's not database-friendly, as to get all fragments we need O(n) operations instead of O(1) with queryset.
Is it possible to create a Django Custom Model Field that references a function or class, instead of a model?
In case you're wondering why i would want this, here's a brief explanation of waht i'm trying to achieve.
Basically i have a FreightTable model, that is used to calculate the value of a freight, so it should have method to do this. But the problem is that there are several different ways to calculate it, and each instance of the FreightTable should calculate on its specific way.
At first i thought about solving this using some kind of polymorphism, but then i would have to create an specific model for each different algorithm, and they would also be in different tables in the DB, what would be a problem for me. I also thought about using Django Polymorphic, but i heard it doesnt really scale well, so it's also not a good idea.
My thought is that if I could just reference this different algorithms on a Model Field, I'll have an ellegant and eficient solution.
My thought is that if I could just reference this different algorithms
on a Model Field
This is a good idea, for example:
CALCULATION_TYPES = [(1, 'Normal'), (2, 'Express')]
class FreightTable(models.Model):
# Normal fields
calculation_type = models.IntegerField(choices=CALCULATION_TYPES)
def calc_normal(self):
pass
def calc_express(self):
pass
def calc_default(self):
pass
Now, for each freight type, you set your calculation method:
ft = FreightType(calculation_type=2)
ft.save()
At the point where you want to display the result of the calculation, fetch the method from the instance, and then call the appropriate method:
call_map = {1: 'calc_normal', 2: 'calc_express'}
ft = FreightTable.objects.get(pk=1)
calculated_value = getattr(ft, call_map(ft.calculation_type))()
Python classes, functions and methods cannot be pickled, so you cannot store the code itself in the database.
What you can do is
1) Store the full dotted path to the function in a CharField. Then resolve the reference to function using zope.dottedname package, and call it.
or
2) Store the calculation code as Python source code in the database as plain text. Then execute it through eval() or dynamic module import using imp module
I am not sure if Django had internal dotted name resolver, you could use it instead of zope.dottedname.
I have many pk-value in a dictionary and I want to update the object with his new value.
to_update = [{'id':id1,'value':value1}, ... ]
Now i'm doing this:
for t in to_update:
Mymodel.objects.filter(pk=t['id']).update(myfield=t['value'])
I think that i can do this in a better way, but i didn't find it.
This is the most efficient way. QuerySet.update() is converted directly to an UPDATE statement, and there is no more efficient way of doing it than that.
I have an hierarchy of models that consists of four levels, all for various good reasons but which to explain would be beyond the scope of this question, I assume.
So here it goes in pseudo python:
class Base(models.Model):
...
class Top(models.Model):
base = FK(Base)
class Middle(models.Model):
top = FK(Top)
created_at = DateTime(...)
flag = BooleanField(...)
class Bottom(models.Model):
middle = FK(Middle)
stored_at = DateTime(...)
title = CharField(...)
Given a title, how do I efficiently find all instances of Base for which that title is met only in the latest (stored_at) Bottom instance of the latest (created_at) Middle instance that has flag set to True?
I couldn't find a way using the ORM, and the way I've seen it, .latest() isn't useful to me on the model that I want to query. The same holds for any convenience methods on the Base model. As I'm no SQL expert, I'd like to make use of the ORM as well as avoid denormalization as much as possible.
Thanks!
So, apparently, without heavily dropping into (some very unwieldy) SQL and not finding any alternative solution, I saw myself forced to resort to denormalized fields on the Base model, just as many as were required for efficiently getting the wanted (filtered) querysets of said model.
These fields were then updated at creation/modificatin time of respective Bottom instances.