Case insensitive Charfield in django models - django-models

I am trying to achieve a category model where name has unique=True,
but practically I can still add same category name with different cases.
i.e. I have a category called Food
I am still able to add food, FOOD, fOod, FOOd
Is their any philosophy behind this? or it is a work in progress.
Cause in real world if I think of Category Food, it will always be food, no matter what case it has used to mention itself.
Thank you in advance to look at this.

To answer my own question:
I have found I can have clean method on my model. So I added
class Category(models.Model):
name = models.CharField(max_length=200, unique=True)
def clean(self):
self.name = self.name.capitalize()
It is capitalising the first letter, which is then handled by the save method, which calls the validate_unique method to raise error.

You can use Postgre specific model field called Citext fields (case insensitive fields).
There are three option at the moment:
class CICharField(**options), class CIEmailField(**options) and class CITextField(**options)
Example:
from django.db import models
from django.contrib.postgres.fields import CICharField
class Category(models.Model):
name = CICharField(verbose_name="Name", max_length=255)
But don't forget to create an extension for the citext fields.
See here.
Basically, you have to add the extension class in the migration file, inside the operations array, before the first CreateModel operation.
# migration file
operations = [
CITextExtension(), # <------ here
migrations.CreateModel(
...
),
...,
]

Setting the column to case-insensitive collation should fix this. You may need to do it at the SQL level.

Related

How to create ArrayField in TortoiseORM

How to create ArrayField() in TortoiseORM
from common.base_model import AbstractBaseModel
from tortoise.fields import CharField, BooleanField, ForeignKeyField, ArrayField
class City(AbstractBaseModel):
name = CharField(max_length=100, unique=True)
district = CharField(max_length=100, null=True)
state = CharField(max_length=100)
country = ArrayField() # not working
is_verified = BooleanField(default=True)
There is no ArrayField in TortoiseORM, here is an article about fields in TortoiseORM from its documentation.
As you can see, there is no matching field in TortoiseORM, so you have to extend the existing field class.
I suggest extending the basic class Field because your subclass' to_db_value method has to return the same type as extended field class' to_db_value method, and in the class Field it's not specified.
Next time, try harder - read the documentation and make better questions (add more info, show your attempts).
To achieve the result you want,which I'm assuming is having a field to hold multiple countries, you'd have to create another table for your country field and have a many to many relationship between that table and your city table,its a more conventional implementation that wont have you extend the existing field class.

Django Model Field Validation

I have a model
class StudentBasicInfo(models.Model):
usn = models.CharField(blank=False,max_length=10,unique=True,validators=[])
my usn will be in format [0-9][A-Za-z][A-Za-z][0-9][0-9][A-Z][A-Z][0-9][0-9][0-9]
I don't know how to write validation code
create a validator. I'd suggest a RegexValidator like so:
from django.core.validators import RegexValidator
...
class StudentBasicInfo(models.Model):
usn = models.CharField(blank=False,max_length=10,unique=True, validators=[RegexValidator(regex='[0-9][A-Za-z]{2}[0-9]{2}[A-Z]{2}[0-9]{3}', message='Error message goes here')])
I took the liberty of shortening your regex by combining groups that were together. If you want to make the error appear next to the field in the admin you'll have to overload a ModelForm.

How to show all fields of model in admin page?

here is the models page
In this picture, only the title shows up on here, I used:
def __unicode__(self):
return self.title;
here is the each individual objects
How do I show all these fields?
How do I show all the fields in each Model page?
If you want to include all fields without typing all fieldnames, you can use
list_display = BookAdmin._meta.get_all_field_names()
The drawback is, the fields are in sorted order.
Edit:
This method has been deprecated in Django 1.10 See Migrating from old API for reference. Following should work instead for Django >= 1.9 for most cases -
list_display = [field.name for field in Book._meta.get_fields()]
By default, the admin layout only shows what is returned from the object's unicode function. To display something else you need to create a custom admin form in app_dir/admin.py.
See here: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display
You need to add an admin form, and setting the list_display field.
In your specific example (admin.py):
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'price')
admin.site.register(Book, BookAdmin)
If you want to include all but the ManyToManyField field names, and have them in the same order as in the models.py file, you can use:
list_display = [field.name for field in Book._meta.fields if field.name != "id"]
As you can see, I also excluded the id.
If you find yourself doing this a lot, you could create a subclass of ModelAdmin:
class CustomModelAdmin(admin.ModelAdmin):
def __init__(self, model, admin_site):
self.list_display = [field.name for field in model._meta.fields if field.name != "id"]
super(CustomModelAdmin, self).__init__(model, admin_site)
and then just inherit from that:
class BookAdmin(CustomModelAdmin):
pass
or you can do it as a mixin:
class CustomModelAdminMixin(object):
def __init__(self, model, admin_site):
self.list_display = [field.name for field in model._meta.fields if field.name != "id"]
super(CustomModelAdminMixin, self).__init__(model, admin_site)
class TradeAdmin(CustomModelAdminMixin, admin.ModelAdmin):
pass
The mixin is useful if you want to inherit from something other than admin.ModelAdmin.
I found OBu's answer here to be very useful for me. He mentions:
The drawback is, the fields are in sorted order.
A small adjustment to his method solves this problem as well:
list_display = [f.name for f in Book._meta.fields]
Worked for me.
The problem with most of these answers is that they will break if your model contains ManyToManyField or ForeignKey fields.
For the truly lazy, you can do this in your admin.py:
from django.contrib import admin
from my_app.models import Model1, Model2, Model3
#admin.register(Model1, Model2, Model3)
class UniversalAdmin(admin.ModelAdmin):
def get_list_display(self, request):
return [field.name for field in self.model._meta.concrete_fields]
Many of the answers are broken by Django 1.10. For version 1.10 or above, this should be
list_display = [f.name for f in Book._meta.get_fields()]
Docs
Here is my approach, will work with any model class:
MySpecialAdmin = lambda model: type('SubClass'+model.__name__, (admin.ModelAdmin,), {
'list_display': [x.name for x in model._meta.fields],
'list_select_related': [x.name for x in model._meta.fields if isinstance(x, (ManyToOneRel, ForeignKey, OneToOneField,))]
})
This will do two things:
Add all fields to model admin
Makes sure that there is only a single database call for each related object (instead of one per instance)
Then to register you model:
admin.site.register(MyModel, MySpecialAdmin(MyModel))
Note: if you are using a different default model admin, replace 'admin.ModelAdmin' with your admin base class
Show all fields:
list_display = [field.attname for field in BookModel._meta.fields]
Every solution found here raises an error like this
The value of 'list_display[n]' must not be a ManyToManyField.
If the model contains a Many to Many field.
A possible solution that worked for me is:
list_display = [field.name for field in MyModel._meta.get_fields() if not x.many_to_many]
I like this answer and thought I'd post the complete admin.py code (in this case, I wanted all the User model fields to appear in admin)
from django.contrib import admin
from django.contrib.auth.models import User
from django.db.models import ManyToOneRel, ForeignKey, OneToOneField
MySpecialAdmin = lambda model: type('SubClass'+model.__name__, (admin.ModelAdmin,), {
'list_display': [x.name for x in model._meta.fields],
'list_select_related': [x.name for x in model._meta.fields if isinstance(x, (ManyToOneRel, ForeignKey, OneToOneField,))]
})
admin.site.unregister(User)
admin.site.register(User, MySpecialAdmin(User))
I'm using Django 3.1.4 and here is my solution.
I have a model Qualification
model.py
from django.db import models
TRUE_FALSE_CHOICES = (
(1, 'Yes'),
(0, 'No')
)
class Qualification(models.Model):
qual_key = models.CharField(unique=True, max_length=20)
qual_desc = models.CharField(max_length=255)
is_active = models.IntegerField(choices=TRUE_FALSE_CHOICES)
created_at = models.DateTimeField()
created_by = models.CharField(max_length=255)
updated_at = models.DateTimeField()
updated_by = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'qualification'
admin.py
from django.contrib import admin
from models import Qualification
#admin.register(Qualification)
class QualificationAdmin(admin.ModelAdmin):
list_display = [field.name for field in Qualification._meta.fields if field.name not in ('id', 'qual_key', 'qual_desc')]
list_display.insert(0, '__str__')
here i am showing all fields in list_display excluding 'id', 'qual_key', 'qual_desc' and inserting '__str__' at the beginning.
This answer is helpful when you have large number of modal fields, though i suggest write all fields one by one for better functionality.
list_display = [field.name for field in Book._meta.get_fields()]
This should work even with python 3.9
happy coding
I needed to show all fields for multiple models, I did using the following style:
#admin.register(
AnalyticsData,
TechnologyData,
TradingData,
)
class CommonAdmin(admin.ModelAdmin):
search_fields = ()
def get_list_display(self, request):
return [
field.name
for field in self.model._meta.concrete_fields
if field.name != "id" and not field.many_to_many
]
But you can also do this by creating a mixin, if your models have different fields.

Computing table name from model name

In my CakePHP application, I have a model like this:
class Duck extends AppModel {
var $name = 'Duck';
function get_table_name() {
$tbl_name = //compute default table name for this model
}
}
I would like to write the function get_table_name() that outputs the default table name for the model. For the example above, it should output ducks.
EDIT:
Several people have pointed out the use of $this->table.
I did small testing and found out the following:
In the question as I have put above, $this->table indeed contains the table name.
However, actually, my code looked more like this:
class Duck extends Bird {
var $name = 'Duck';
function get_table_name(){
$tbl_name = //comput default table name for this model
}
}
class Bird extends AppModel {
}
In this case $this->table is empty string.
I went with this approach because I wanted to share some code between two of my models. Looks like this is not a good way to share code between models which need some common functionality.
You're looking for the Inflector class.
Inflector::tableize($this->name)
(tableize calls two Inflector methods to generate the table name: underscore() and pluralize())
Edit:
According to the source code, $this->table should contain the name of the table that CakePHP will use for the model, but in my experience this isn't always set. I'm not sure why.
To get the name of the table that the model is currently using, you can use: $this->table. If you don't manually change the model's table conventions, this may be the most useful in the case of CakePHP ever changing its conventions to use table names using something other than Inflector.
CakePHP's Inflector
function get_table_name() {
$tbl_name = Inflector::pluralize($this->name);
}
OR the tableize method
function get_table_name() {
$tbl_name = Inflector::tableize($this->name);
}
Edit
This also addresses the apparent "ghost" issue with $this->table in the Model.
Digging around in the __construct for Model I discovered two things:
Cake uses Inflector::tableize() to get the table name. This alone is enough to warrant using tableize over pluralize. You'll get consistent results.
$this->table is not set by the Model::__construct() unless $this->useTable === false AND $this->table === false.
It appears that if you know you haven't set $this->useTable to false you should be able to use this over $this->table. Admittedly though I only briefly scanned the source and I haven't really dug deep enough to say why $this->table isn't working sometimes.
To get the full table name for a model you have to take the table prefix into account.
$table = empty($this->table) ? Inflector::tableize($this->name) : $this->table;
$fullTableName = $this->tablePrefix . $table;
I used to use inflector to get the table name from model's name
$tableName = Inflector::pluralize(Inflector::underscore($model));
but this is not really universal, using useTable looks better, by default it will contain table's name by convention, and if you have a table that does not match the conventions, then you should manually specify it by useTable. So, in both cases the result will be correct
$this->User->useTable

AppEngine Datastore get entities that have ALL items in list property

I want to implement some kind of tagging functionality to my app. I want to do something like...
class Item(db.Model):
name = db.StringProperty()
tags = db.ListProperty(str)
Suppose I get a search that have 2 or more tags. Eg. "restaurant" and "mexican".
Now, I want to get Items that have ALL, in this case 2, given tags.
How do I do that? Or is there a better way to implement what I want?
I believe you want tags to be stored as 'db.ListProperty(db.Category)' and then query them with something like:
return db.Query(Item)\
.filter('tags = ', expected_tag1)\
.filter('tags = ', expected_tag2)\
.order('name')\
.fetch(256)
(Unfortunately I can't find any good documentation for the db.Category type. So I cannot definitively say this is the right way to go.) Also note, that in order to create a db.Category you need to use:
new_item.tags.append(db.Category(unicode(new_tag_text)))
use db.ListProperty(db.Key) instead,which stores a list of entity's keys.
models:
class Profile(db.Model):
data_list=db.ListProperty(db.Key)
class Data(db.Model):
name=db.StringProperty()
views:
prof=Profile()
data=Data.gql("")#The Data entities you want to fetch
for data in data:
prof.data_list.append(data)
/// Here data_list stores the keys of Data entity
Data.get(prof.data_list) will get all the Data entities whose key are in the data_list attribute

Resources