Login

Tag "models"

Snippet List

Compare objects list and get a list of object to inserted or updated

**Problem** You have an input `json` with which you will create a list of objects, you have to validate that the object will be created if it not exists, if exists determine whether to upgrade or discard depending of they have not undergone any changes. Solution 1) With the input `json` will be created the list of objects of the class that we insert or updatee 2) Read all fields in the database, using one of the fields as key to creating a dictionary with the objects in the database 3) Compare the objects and determine if it will be updated, inserted or discarded Django problem: by default only compares the level objects using the primary key (id). Compare field by field is the solution to determine if the object has changed. hints: The _state field is present in every object, and it will produce a random memory location, You can find cache fields so you need to remove these begins with underscore `_`. The fields excluded can be fk, and these fields produce field_id, so you will needs to exclude it class Country(models.Model): # country code 'MX' -> Mexico code = models.CharField(max_length=2) name = models.CharField(max_length=15) class Client(models.Model): # id=1, name=pedro, country.code=MX, rfc=12345 name = models.CharField(max_length=100) country = models.ForeignKey(Country) rfc = models.CharField(max_length=13) Country.objects.create(**{'code': 'MX', 'name': 'Mexico'}) # creating the country Client(**{'id':1, 'name':'pedro', 'country': country, 'rfc':12345}) # creating the client obj_db = Client.objects.get(id=1) country = Country.objects.get(code='MX') obj_no_db = Client(**{'id':1, 'name':'pedro', 'country': country, 'rfc':12345}) obj_db == obj_no_db # True obj_no_db = Client(**{'id':1, 'name':'pedro', 'country': country, 'rfc':1}) obj_db == obj_no_db # True # but isn't True because the rfc has change, how can compare field by field obj_db.rfc == obj_no_db.rfc # False, I was expected this result when compare obj_db == obj_no_db because they are not equal **Solution to compare field by field** _obj_1 = [(k,v) for k,v in obj_db.__dict__.items() if k != '_state'] _obj_2 = [(k,v) for k,v in obj_no_db.__dict__.items() if k != '_state'] _obj_1 == _obj_2 # False This is only for one object, and you can include in `__eq__` method in your model, but what happen if you need compare a list of object to bulk for insert or update with `django-bulk-update`. Well my snipped pretends solve that. so **How can use it.** obj_list = [<Object Client>, <Object Client>, <Object Client>, <Object Client>] get_insert_update(Client, 'id', obj_list) exclude_fields = ['country'] get_insert_update(Client, 'id', obj_list, exclude_fields=exclude_fields)

  • models
  • bulk
Read More

Another Multiform

MultiForm and MultiModelForm Based on a PrefixDict class I wrote and thus very lean. Lacks a little documentation, though class MyMultiForm(ModelMultiForm): class Meta: localized_fields = '__all__' form_classes = OrderedDict(( ('form1', Form1), ('form2', Form2), )) Subfields are named `form-name` `prefix_sep` `subfield-name`. `prefix_sep` defaults to `-`. For access in templates, use `form.varfields`, which uses `var_prefix_sep` (default: `_`), instead. multiform.varfields()['form1_field1']

  • models
  • forms
  • multiform
Read More

IntegerRangeField

Django models IntegerField that get max_value and min_value in it's constructor and validate on it. It's initialize the formfield with min_value and max_value, too.

  • models
  • fields
  • IntegerField
Read More

Django admin autoregister

Official GitHub page: https://github.com/Mimino666/django-admin-autoregister One call to autoregister_admin() automatically creates and registers admin views for all the models in the specified module with intelligent linking between ForeignKey, OneToOneField and ManyToManyField fields.

  • models
  • admin
  • auto
  • autoregister
Read More

Get derived model instance

Get derived model without storing their names or content types in databases. You write only one line, it expands into only one SQL-query (with many LEFT OUTER JOIN's). Model definition example: class BaseModel(models.Model): foo = models.IntegerField(null=True) derived = DerivedManager() class FirstChild(BaseModel): bar = models.IntegerField(null=True) class SecondChild(BaseModel): baz = models.IntegerField(null=True) How to use: >>> f = FirstChild.objects.create() >>> s = SecondChild.objects.create() >>> print list(BaseModel.objects.all() [<BaseModel object 1>, <BaseModel object 2>] >>> print list(BaseModel.derived.all() [<FirstChild object 1>, <SecondChild object 2>] >>> print BaseModel.derived.get(pk=s.pk) <SecondChild object 2>

  • models
  • orm
  • inheritance
Read More

Extended i18n base model

This snippet is an extension of [i18n base model for translatable content](http://djangosnippets.org/snippets/855/) so all the same usage applies. I have extended this module in several ways to make it more fully featured. * `I18NMixin` can be an additional (via multiple inheritance) or alternative superclass for your models juxtaposed with an `I18NModel`. * Adds a property `_` to access the appropriate I18NModel. `trans` aliases this (or rather vice versa) for template access. * In a call to `.filter` you can query on translated fields by wrapping those fields in a call to i18nQ. I like to import this as _ if I haven't already used that import. * A call to I18NFieldset will return an inline for use in the builtin admin app. I like to call this inline to the assignment to inlines. * If you need abstracted access to the I18N model from a model, I've added a property I18N referring to it. I've been using this with great convenience and stability.

  • models
  • i18n
  • metaclass
  • translated-content
Read More

decorator to add GUID Field to Django Models

A decorator to add a GUID Field to a Django Model. There are other bits of code out there that do similar things, but it was important for the field to have a unique value _before_ it is saved in the database. The contribute_to_class method therefore registers the field class with the post_init signal of the class it's being added to. The handler for that signal is where field initialization is done.

  • models
  • fields
  • decorators
Read More

PatchModelForm - A ModelForm subclass with the semantics of the PATCH HTTP method

Use this class to partially update one or more fields of a model. Only the fields that are bound to the form via the "data" parameter in the constructor get updated. All automatically generated fields have their "required" attribute set to False. Example 1: from django.contrib.auth.models import User class PatchUserForm(PatchModelForm): class Meta: model = User user = User.objects.get(username='old_username') form = PatchUserForm(data={'username':'new_username'}, instance=user) form.is_valid() form.save() Example 2: from django.contrib.auth.models import User class PatchUserForm(PatchModelForm): class Meta: model = User user = User.objects.get(pk=35) form = PatchUserForm(data={'last_name':'Smith', 'is_staff': True}, instance=user) form.is_valid() form.save()

  • models
  • rest
  • update
  • patch
  • partial-update
Read More

Binding signals to abstract models

Intro ----- I found a question on SO for which Justin Lilly's answer was correct but not as thorough as I'd like, so I ended up working on a simple snippet that shows how to bind signals at runtime, which is nifty when you want to bind signals to an abstract class. Bonus: simple cache invalidation! Question -------- [How do I use Django signals with an abstract model?](http://stackoverflow.com/questions/2692551/how-do-i-use-django-signals-with-an-abstract-model) I have an abstract model that keeps an on-disk cache. When I delete the model, I need it to delete the cache. I want this to happen for every derived model as well. If I connect the signal specifying the abstract model, this does not propagate to the derived models: pre_delete.connect(clear_cache, sender=MyAbstractModel, weak=False) If I try to connect the signal in an init, where I can get the derived class name, it works, but I'm afraid it will attempt to clear the cache as many times as I've initialized a derived model, not just once. Where should I connect the signal? Answer ------ I've created a custom manager that binds a post_save signal to every child of a class, be it abstract or not. This is a one-off, poorly tested code, so beware! It works so far, though. In this example, we allow an abstract model to define CachedModelManager as a manager, which then extends basic caching functionality to the model and its children. It allows you to define a list of volatile keys that should be deleted upon every save (hence the post_save signal) and adds a couple of helper functions to generate cache keys, as well as retrieving, setting and deleting keys. This of course assumes you have a cache backend setup and working properly.

  • managers
  • models
  • cache
  • model
  • manager
  • signals
  • abstract
  • signal
  • contribute_to_class
Read More

Prefetch id for Postgresql backend

When uploading a file or image, you need to put it somewhere that's not going to be orphaned by a change in the model. You could use a globally unique value like a uuid, but the django id autofield is a much shorter surrogate field that can be used in a friendly path to the object. The problem with id autofields is that they don't exist when the object is created for the first time - so all files using the id get uploaded to a location 'None' on first save, increasing the likelihood of name collisions. This postgresql only snippet fetches the next id in a way that is safe for concurrent access. This snippet only works on postgresql because neither sqlite or mysql have a nextval equivalent. Instead you would have to lock the table for writes and select the last value inserted incrementing it yourself.

  • models
  • filefield
Read More

93 snippets posted so far.