Imagine that I have a model that describes the printers that are in the office. They can be ready to work or not (perhaps in the storage area or it was purchased, but not yet in the office). The model should have a field representing the physical location of the printer ("Secretariat", "Reception", ...). There cannot be two repeating places, and if it does not work, it should not have a place.
I want to have a list in which all printers are displayed, and for each of them there are places where they are (if any). Something like that:
ID | Location 1 | "Secretary office" 2 | 3 | "Reception" 4 |
With this, I can know that two printers (1 and 3) work, and the others - lines (2 and 4).
The first approach for the model should be something like this:
class Printer(models.Model): brand = models.CharField( ... ... location = models.CharField( max_length=100, unique=True, blank=True )
But this does not work properly. You can only store one register in one empty space. It is stored as an empty string in the database and does not allow inserting more than once (the database says that there is another empty string for this field). If you add the parameter "null = True" to this, it will behave in a similar way. This means that instead of the NULL value in the corresponding column, the default value is an empty row.
Searching the Internet I found http://www.maniacmartin.com/2010/12/21/unique-nullable-charfields-django/ which tries to solve the problem in many ways. He says that perhaps the cleanest is the last, in which he subclasses the CharField class and overrides some methods to store different values ββin the database. Here is the code:
from django.db import models class NullableCharField(models.CharField): description = "CharField that obeys null=True" def to_python(self, value): if isinstance(value, models.CharField): return value return value or "" def get_db_prep_value(self, value): return value or None
It works great. You can store multiple registers without space, because instead of inserting an empty string, it saves NULL. The problem is that it shows empty spaces with Nones instead of an empty line.
ID | Location 1 | "Secretary office" 2 | None 3 | "Reception" 4 | None
I suggested that there is a method (or several) that should indicate how the data should be transformed between the model and the database class manager in two ways (a database for modeling and modeling in a database).
Is this the best way to have a unique blank CharField?
Thanks,