How to provide model configuration presets in Django - django-models

so what I am trying to achieve is the following:
I have two models A and B which have a OneToOne relationship. Instances of model A are always created before their respective model B instances. Dependent on a parameter, I want to be able to initialize an instance of model b with different initial values.
What I've come up with is to define a ProtoTypeModel and subclass it with the actual Model like so:
from django.db import models
#other imports
class PrototypeB(models.Model):
#define all fields
class B(PrototypeB):
pass
By using dict = PrototypeB.objects.filter(**my criteria).values()[0] or a custom Serializer from Django Rest Framework, I will get a dict which I can then use to instantiate my instance of model B : B.objects.create(**dict).
Is this the proper way to do so or am I missing a huge point?
Best,
D

In case anyone stumbles upon the same question on his path, here's how I did it.
First I thought about implementing the solution I mentioned above. However, researching about multi table inheritance, I found that this is actually a non functioning one.
The multi table inheritance will create an implicit OneToOne _ptr field, which will trigger cascade deleting behavior, causing my arche type models to be deleted, when an instance of B is deleted.
I went along implementing two models PrototypeB and B which works perfectly fine.

Related

app engine ndb - how to load entity by key using id?

I am trying to load an entity by key using the id it was assigned by the datastore but I don't see any api method to do this (using NDB). I thought I would be able to make a Key from an integer id and use key.get() to load the entity, but I don't see a way to make a key from just an id. I suspect I am missing something obvious here. How should I load an entity where I only know the id of it?
Another way: ndb.Key(YourModel, id).get().
YourModel.get_by_id() gets a model instance by id.
here the docs:
https://developers.google.com/appengine/docs/python/ndb/modelclass#Model_get_by_id
don't think you can't get an entity by id without knowing the kind because instances of different Model classes can have the same id/key_name
Models in NDB don't define their key type as part of the model. This is nifty in that you can have one given model type that is accessible through multiple different kinds of keys and parents, which makes them more flexible. But it's somewhat problematic because it isn't always clear what the key represents or where it comes from.
So in cases where there's only ever one kind of key for a given model (which is almost every model), I like to create a class method for generating that key, which adds a bit of semantic clarity:
class Book(ndb.Model):
title = ndb.StringProperty()
pages = ndb.IntegerProperty()
#classmethod
def make_key(cls, isbn):
return ndb.Key(cls, isbn)
b = Book.make_key('1234-5678').get()
Sure the added code is not strictly necessary, but it adds clarity and makes my models more long-term maintainable.
You can parse the id to key string:
key = ndb.Key(YourModel, id).urlsafe().
and then:
result = YourModel.query(YourModel.key== key).get().

Django ModelForm save using db_alias param "using"

Is it possible to save ModelForm object data with db_alias different than "default"
my_form = MyModelForm(request.POST)
my_form.save(commit=True,using="db_alias")
as well as saving data with model instance?
Thank you.
Short Answer: Unfortunately ,you can't save the form that way. If you form doesn't contain ForeignKey or m2m fields (or you are controlling them yourself, for example using an autocompletefield, etc.), you can handle the object after the form:
_obj = _form.save(commit=False)
_obj.save(using=_db_alias)
Long answer: If you want the modelform to behave like a normal one with ForeignKeys and m2m-fields, something like:
# The form's foreign_keys and m2m-fields get the data from the db_alias database
# and evertyhing is sdisplayed correctly on the template.
_form = myModelForm(request, db_alias=_db_alias)
# The form saves to the correct DB and foreigns & M2ms are matched correctly in this DB
# _form.save()
Although this would be ideal, you just can't use this behaviour. There are many DB hooks that you need to alter in Django code to get this working. What I have done is to create a new modelform class from the base modelform, and get the (partial) functionality described before.
Hope this helps, and also hopping a better solution comes soon.

Django: cannot detect changes on many-to-many field with m2m_changed signal - auditing at model-level

I'd like to keep track on what field has changed on any model (i.e. audit at model level since it's more atomic, not at admin/form-level like what django and django-reversion can already do). I'm able to do that for any field using pre/post save/delete signals. However, I have a problem of doing that on an m2m field.
For the code sample below, i define 'custom_groups' m2m field in user change form since it's a reverse relation. When user saves the form on admin interface for example, I'd like to log if there's a change in 'custom_groups' field.
Model:
from django.contrib.auth.models import User
class CustomGroup(models.Model):
users = models.ManyToManyField(User, related_name='custom_groups')
ModelForm:
class CustomUserChangeForm(UserChangeForm):
custom_groups = forms.ModelMultipleChoiceField(required=False, queryset=CustomGroup.objects.all())
The problem with using m2m_changed signal is that i can't check what has actually changed for the case where the m2m field is updated using assignment operator:
user.custom_groups = self.cleaned_data['custom_groups']
This is because internally django will perform a clear() on *custom_groups*, before manually adding all objects. This will execute pre/post-clear and then pre/post save on the m2m field.
Am I doing all this the wrong way? Is there a simpler method that can actually work?
Thanks!
I had a similar problem and I think I could solve it. I don't know how you are using the m2m_changed but it should be on models.py and should be similar to something like this:
signals.m2m_changed.connect(your_function, sender=CustomGroup.users.through)
Now, I would create a signals.py file containing that function, and the following code should print you the options that you have selected:
def your_function(sender, instance, action, reverse, model, pk_set, **kwargs):
if action == 'post_add':
for val in pk_set:
print val
Now, you know the updated values. I hope this could solve your problem.

DRY unique objects in Django

I want to ensure an object is unique, and to throw an error when a user tries to save it (e.g. via the admin) if not? By unique, I mean that some of the object's attributes might hold the same values as those of other objects, but they can't ALL be identical to another object's values.
If I'm not mistaken, I can do this like so:
class Animal(models.Model):
common_name = models.CharField(max_length=150)
latin_name = models.CharField(max_length=150)
class Meta:
unique_together = ("common_name", "latin_name")
But then each time I refactor the model (e.g. to add a new field, or to change the name of an existing field), I also have to edit the list of fields in the parenthesis assigned to unique_together. With a simple model, that's OK, but with a substantial one, it becomes a real hassle during refactoring.
How can I avoid having to repeat typing out the list of field names in the unique_together parenthesis? Is there some way to pass the list of the model's fields to a variable and to assign that variable to unique_together instead?
Refactoring models is a rather expensive thing to do:
You will need to change all code using your models since field names correspond to object properties
You will have to change your database manually since Django cannot do this for you (at least the version I used the last time when I worked with Django couldn't)
Therefore I think updating the list of unique field names in the model meta class is the least issue you should worry about.
EDIT: If you really want to do this and all of your fields must be "unique together", then the guy at freenode is right and you'll have to write a custom metaclass. This is quite complicated and errorprone, plus it might render your code incompatible to future releases of Django.
Django's ORM "magic" is controlled by the metaclass ModelBase (django.db.models.base.ModelBase) of the generic base class Model. This class is responsible to take your class definition with all fields and Meta information and construct the class you will be using in your code later.
Here is a recipe on how you could achieve your goal:
Subclass ModelBase to use your own metaclass.
Override the method __new__(cls, name, bases, dict)
Inspect dict to gather the Meta member (dict["Meta"]) as well as all field members
Set meta.unique_together based on the names of the fields you gathered.
Call the super implementation (ModelBase.__new__)
Use the custom metaclass for all your unique models using the magic member __metaclass__ = MyMetaclass (or derive an abstract base class extending Model and overriding the metaclass)

Silverlight / .NET RIA Services - Exposing a custom property to the client

I have a table in my database called "Task". Task has the following fields:
- ID
- Description
- AssignedUserID
- TaskTypeID
I am accessing this table through a class that was created automatically after I used an ADO.NET Entity Data Model. I can load and show the fields mentioned above in a DataGrid in my Silverlight application. However, AssignedUserID and TaskTypeID are not very descriptive. So I decided to create a stored procedure that gets the tasks and the user and task type names through their respective lookup tables. This is where the problem lies.
I want to create some custom properties in the automatically generated "Task" class. The custom properties would be named "AssignedUserName" and "TaskType". I then want to make these properties available to my Silverlight client. However, I cannot seem to figure out how to get them exposed to my Silverlight client.
Can someone help?
Thank you
If your EDM is in the same project as the DomainService you can do this:
create a partial class on the Entity type, and add your calculated property in there.
name the file **.shared.cs
it will then be auto-shared with the client/Silverlight code.
Edit:
I was assuming that you could do this calculation in app logic rather than use an sp, which seems more straightforward to me.
If you do use an SP, you'll need to use the Function Import feature in the designer to map the SP to a function in the EDM. This function can then return entities, with properties mapped however you like.
An easier way would be to just use the object model: Have Task.AssignedUser and Task.TaskType objects off of your Task class. Map these to lookup tables in your db. This will work out-of-the box (assuming the Id's are FK's to those lookup tables).
So, a couple options:
use app-logic--properties in a partial class to return the descriptions
use the object model driven by FKs to lookup tables, then just access Task.AssignedUser.Name or Task.TaskType.Description
use a function import to access the SP and map the returned values to entity properties
1 or 2 being the best options IMHO.
Another approach might be to update your EF model to include the lookup tables, add Associations between the tables, add [Include]s in the (auto-gen'd) metadata class and let EF and RIA do it for you. Maybe.

Resources