DRY unique objects in Django - django-models

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)

Related

How can I modify the meta data of any field using apex

I am trying to change the metadata of fields of a object in salesforce using Apex. For example I am trying to make all required field non-required. I was able to retrieve all the required fields using the schema class and using methods like isNillable(). I wanted to ask if there is any way I can modify the metadata.
I have searched a lot regarding this but could not find any helpful results.
Schema.DescribeSObjectResult a_desc = objects.get(Name_of_of_object_whose_fields_are_to_be_retrieved).getDescribe();
Map<String, Schema.SObjectField> a_fields = a_desc.fields.getMap();
Set<string> x=a_fields.keySet();
//I am making a map of fieldname and bool(field required or not)
Map<String,boolean> result=new Map<String,boolean>();
for(String p:x)
result.put(p,a_fields.get(p).getDescribe().isCreateable() && !a_fields.get(p).getDescribe().isNillable() && !a_fields.get(p).getDescribe().isDefaultedOnCreate());
//what I want is to modify isNillable and other attributes and make these changes to the fields.
You can't make all required fields non-required because many of them are required at the database level and cannot be modified.
For example, the Name field (on any object that has a Name field) is always required. You cannot change this property. Likewise, Master-Detail relationship fields are always required, on standard and child objects.
To change the metadata of custom fields that are modifiable, you would have to use the Metadata API. It's not available in Apex, unless you use a wrapper like apex-mdapi. As a warning, modifying your org's metadata in a broad-based way via Apex is dangerous. You can cause damage to your org and its function in this way very easily. I strongly encourage you not to attempt to do this. Required fields are required for a reason.

Using UUID for id on Pages

Just getting started with Wagtail. To support interoperability with a legacy system, I'd like to have the id/pk of my Page objects be UUIDs instead of Integers. I tried just adding a id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) to my class that inherits from Page but I get an error Local field u'id' clashes with field of similar name from base class 'Page'
Is there a simple way to make id be a UUID? Or, do I just need to call it something besides id?
There won't be a simple way to do this, unfortunately - the assumption that IDs are numeric is baked in to the database schema, URL routes, rich text data representation and various other places in Wagtail's design.
Would it be an option to add your UUID column as a new field on your model (named something like legacy_id), and look up on that whenever you need to interoperate with the legacy system - but otherwise leave the primary key as numeric?

How to provide model configuration presets in Django

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.

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

Write-once fields in Django models

I'm having a pretty hard time trying to create a write-once field in a Django model. Ideally I'd want it to work like a final variable, although I can settle for simply preventing it from being edited through the admin.
I know there is a solution for read-only fields, but it also affects the add form, and I don't want the field to be read-only there.
Use get_readonly_fields(), and return a tuple with the write-once field name if obj exists, or an empty tuple if obj is None.
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_readonly_fields

Resources