Django model naming convention - django

What is the preferred naming convention for Django model classes?

Django models are just Python classes, so the Python naming conventions detailed in PEP-8 apply.
For example:
Person
Category
ZipCode
If Django fails to pluralize the class name properly when creating the corresponding table, you can easily override the pluralization by setting a custom verbose_name_plural field in an inner META class. For example:
class Story(models.Model):
...
class Meta:
verbose_name_plural = "stories"

As far as I know, the idea is that the class name should be singular and should use SentenceCase with no spaces. So you'd have names like:
Person
TelephoneNumber
Then the Django admin tool knows how to pluralise them. Doesn't work so nicely for names like:
Category
which gets pluralised as Categorys, but there we go...
Apart from that, just give it a name that means something to you and succinctly sums up what the class is meant to represent.
Ben

In most of programming languages, people prefer give a singular names to the objects/models because these models are also represented by tables in your database system. The minimalism is a good choice everytime to avoid some meaning conflicts in the future.
To exemplify;
https://stackoverflow.com/a/5841297/2643226

In adition, when you need related objects for a Model of more than one word, you can use the _set attribute. Example:
class ProcessRoom(models.Model):
...
plant = models.ForeignKey("Plant", verbose_name='planta', on_delete=models.CASCADE)
Then, related objects will be:
plant = Plant.object.get(id=1)
process_rooms = plant.processroom_set.all

Related

Django admin shows models name with extra "s" at the end

I'm new to Django. In the admin panel, the name of the models has an extra "s" at the end. How can I fix that?
Why is django-admin adding an 's'
There is a naming convention in Django the models are named in the singular. So your classes should be named:
class Comment(models.Model):
...
class Note(models.Model):
...
An instance of such a class represents a single comment, not a set of comments. Likewise consider the following
# doesn't really make sense
Comments.objects.get(...)
# reads much better
Comment.objects.get(...) #e.g. get from the comment objects
This is so much of a convention that Django admin expects for your classes to be named in the singular. For this reason, Django adds on an 's' as a standard way of pluralising your class names. (This will admittedly not work for all words and is very anglo-centric, but as an override, Django provides the verbose_name_plural meta-attribute).
How to fix it:
Rename your classes so they are in the singular. This will make your code a lot more readable to anyone who is used to reading django. It will also make your models named in a way consistent with other third-party packages. If your class names are not in English, or do not pluralise simply by appending an s, use verbose_name_plural e.g:
Class Cactus(models.Model):
class Meta:
verbose_name_plural = 'Cacti'
Add a meta class to your model and set verbose_name_plural (https://docs.djangoproject.com/en/3.2/ref/models/options/#verbose-name-plural). Ideally name your classes as singular (in this case you'd have class Comment(models.Model).
class Comments(models.Model):
class Meta:
verbose_name_plural = 'Comments'
Good read:
https://simpleisbetterthancomplex.com/tips/2018/02/10/django-tip-22-designing-better-models.html#:~:text=Always%20name%20your%20models%20using,not%20a%20collection%20of%20companies.

Django models and relationships . error [duplicate]

I want to create an object that contains 2 links to Users. For example:
class GameClaim(models.Model):
target = models.ForeignKey(User)
claimer = models.ForeignKey(User)
isAccepted = models.BooleanField()
but I am getting the following errors when running the server:
Accessor for field 'target' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'target'.
Accessor for field 'claimer' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'claimer'.
Can you please explain why I am getting the errors and how to fix them?
You have two foreign keys to User. Django automatically creates a reverse relation from User back to GameClaim, which is usually gameclaim_set. However, because you have two FKs, you would have two gameclaim_set attributes, which is obviously impossible. So you need to tell Django what name to use for the reverse relation.
Use the related_name attribute in the FK definition. e.g.
class GameClaim(models.Model):
target = models.ForeignKey(User, related_name='gameclaim_targets')
claimer = models.ForeignKey(User, related_name='gameclaim_users')
isAccepted = models.BooleanField()
The User model is trying to create two fields with the same name, one for the GameClaims that have that User as the target, and another for the GameClaims that have that User as the claimer. Here's the docs on related_name, which is Django's way of letting you set the names of the attributes so the autogenerated ones don't conflict.
The OP isn't using a abstract base class... but if you are, you will find that hard coding the related_name in the FK (e.g. ..., related_name="myname") will result in a number of these conflict errors - one for each inherited class from the base class. The link provided below contains the workaround, which is simple, but definitely not obvious.
From the django docs...
If you are using the related_name
attribute on a ForeignKey or
ManyToManyField, you must always
specify a unique reverse name for the
field. This would normally cause a
problem in abstract base classes,
since the fields on this class are
included into each of the child
classes, with exactly the same values
for the attributes (including
related_name) each time.
More info here.
Sometimes you have to use extra formatting in related_name
- actually, any time when inheritance is used.
class Value(models.Model):
value = models.DecimalField(decimal_places=2, max_digits=5)
animal = models.ForeignKey(
Animal, related_name="%(app_label)s_%(class)s_related")
class Meta:
abstract = True
class Height(Value):
pass
class Weigth(Value):
pass
class Length(Value):
pass
No clash here, but related_name is defined once and Django will take care for creating unique relation names.
then in children of Value class, you'll have access to:
herdboard_height_related
herdboard_lenght_related
herdboard_weight_related
I seem to come across this occasionally when I add a submodule as an application to a django project, for example given the following structure:
myapp/
myapp/module/
myapp/module/models.py
If I add the following to INSTALLED_APPS:
'myapp',
'myapp.module',
Django seems to process the myapp.mymodule models.py file twice and throws the above error. This can be resolved by not including the main module in the INSTALLED_APPS list:
'myapp.module',
Including the myapp instead of myapp.module causes all the database tables to be created with incorrect names, so this seems to be the correct way to do it.
I came across this post while looking for a solution to this problem so figured I'd put this here :)
Just adding to Jordan's answer (thanks for the tip Jordan) it can also happen if you import the level above the apps and then import the apps e.g.
myproject/
apps/
foo_app/
bar_app/
So if you are importing apps, foo_app and bar_app then you could get this issue. I had apps, foo_app and bar_app all listed in settings.INSTALLED_APPS
And you want to avoid importing apps anyway, because then you have the same app installed in 2 different namespaces
apps.foo_app
and
foo_app

Displaying all fields of Foreign Key Model

What I want is to retrieve all the fields belonging to a Model of a foreign key.
My models for example:
class BaseProduct(models.Model):
name = models.CharField(max_length=256)
variant = models.CharField(max_length=256, default='N/A')
type = models.ForeignKey(ProductType)
class ProductType(models.Model):
name = models.CharField(max_length=256,blank=False,null=False)
sofa = models.ForeignKey(SofaProduct, blank=True, null=True)
toaster = models.ForeignKey(ToasterProduct, blank=True, null=True)
These are just examples, there can be any number of ProductType models each with any number of fields.
In my template I can display all the fields of the BaseProduct by using the BaseProduct ID. What I want is to display all the fields of the FK.
For example if type = sofa in BaseProduct, I need to retrieve and display all sofa fields as well as BaseProduct fields.
(disclaimer: I have a tendency to give really long answers. You'll have to forgive me for that)
First rule of schema design - It should reflect your real world business logic (not the actual business action mind you, just the implications of the relationships). For example, if I have a class Person I can create a class Pet with a foreginKey to Person which translates to - every person can have multiple pets.
If we apply that logic to your schema we see that ProductType is a class that has a foreignKey to both Sofas and Toasters, which means each Toaster can have multiple Sofas and vice versa. Last time I checked, I never heard of a Sofa that had a Toaster.
In other words - you need to think what you're actually trying to achieve here. I'm guessing BaseProduct is a basic class that has common fields, and Sofa and Toaster are different types of products. Since they are different, they have their own special fields, and shouldn't be related, so it makes sense to have them as separate models. So why do you even need ProductType? To define the name Toaster? You're already defining an entire model! Why do you need to keep its name on a different table (and not, say, some custom method that always returns "I am a toaster, hear me roar")?
My best guess is that you want to be able to define new types of products on the go. However, if you intend to keep them separated on the model level, then you'll have to create a model for each new product. And if you want to be able to simple define a new model with ProductType, then you either need to have one Product class to manage them all, or you want a complicated dynamic system that can create new models on the fly.
Let's break those options down:
Create a generic product and a type class, like you did there:
class ProductType(models.Model):
name = models.CharField(max_length=256,blank=False,null=False)
class Product(models.Model):
name = models.CharField(max_length=256)
variant = models.CharField(max_length=256, default='N/A')
type = models.ForeignKey(ProductType)
Now each product can only be of one type, and you can always create new types on the go. This of course means all Product objects will share the same fields, and is very limiting. You won't have the same flexibility for each type like you would before (no sofa-only fields), but on the other hand it will be easier to create dynamic types of objects - you just define a new ProductType and bam you have a whole new group of products.
Create a basic abstract Product model, and define a new sub-model for each new type of product. You'll have a lot more flexibility for each one, but defining new types will always require defining a new model and setting up a table for it. With this scheme you don't need the ProductType object at all because the different models define the different types (there's no need for duplicity).
You can create some kind of admin page for the process, but it's not going
to be very easy to setup, and you might find yourself eventually with too many tables
(which can be especially problematic if you need to sometimes query
on all products - you'll have to join a lot of different tables,
which is not very efficient).
Use a non-relational database with some dynamic-models know how and disco*
*ok, it's actually more complicated than that, but the explanation on how to combine them is way too long, even for my answer. If it seems over your head, forget about it. If you have some idea about how non-relation databases work, you can probably figure it out yourself
Your question is somewhat unclear.
I think you want Django modal forms to display all fields of an modal.
def ListForm(Forms.form):
model = MyModel
fields='__all__' #Sets display all
fk_name ="Model_to_use" #Is needed when your model has more then one fk
Django model form
You can use _set for accessing related objects. For example, if you have two models like these:
class MyModel(models.Model):
name = models.CharField(max_length=200)
somedata = models.CharField(max_length=200)
class AnotherModel(models.Model):
name = models.CharField(max_length=256,blank=False,null=False)
referral = models.ForeignKey(MyModel)
type = models.CharField(max_length=256,blank=False,null=False)
you can access the name field of AnotherModel with
>>> m = MyModel.objects.get(id=1)
>>> m.AnotherModel_set.all()[0].name
See: https://docs.djangoproject.com/en/dev/topics/db/queries/#related-objects
On a side note, you should probably rethink your models structure, as yuvi pointed out.

Defining dependent Django Model Fields

I have to define a model where one of the fields depends on the other.
I am storing commodity trades, and the grades of the commodities vary based on the kind of commodity. For example if I store a coal and an iron trade I need to specify what is the quantity of each grade being traded.
Example:
{'Gradeā€“I':500, 'Grade-II':1000, 'Washery-Grade-I':0, 'Washery-Grade-II':0, 'Washery-Grade-III':100}
{'Fe 65%+':10, 'Fe 60-65%':55,'Fe 55-60%':0}
One possible approach is storing the commodity type as a CharField with choices and serializing the the grade quantity and storing it as a JSONField.
class TradeRetail (models.Model):
commodity_type = models.CharField(max_length=5, choices=(('CO','COAL'),('IO','IRON-ORE'),('WTI','WTI'),), blank=False)
grade_quantity = JSONField()
My questions are:
a) Is this the neatest way to create a Model?
b) How do I define the relationships between grade_quantity and commodity_type to generate appropriate forms to obtain user inputs?
c) Will all the custom validations I write sit in the clean() function?
If I get correctly your problem, I think it would more "Django-compliant" to define two models: one containing the commodity_type, and one containing the grade_quantity. Then, you can create a foreign key in commodity_type to link it with grade_quantity.
As general documentation, you may read https://docs.djangoproject.com/en/1.7/topics/db/examples/one_to_one/
Exemple:
class Commodity (models.Model):
type = models.CharField(...)
quantity = models.ForeignKey('Commodity')
class Grade (models.Model):
type = models.<your type adapted to the grade quantity field>
Warning: I haven't test this exact example, but it looks like what you're trying to achieve. Have a look at the page https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey
For your questions:
a) For tips on how to create models, see the first links with OneToOne examples. Usually, it is useful to add a str(self) function for displaying correctly the name of the model instance. Read carefully the examples in Django documentation to have tips about how to correctly write your model (usually you define first the fields, then the methods of the models, and often the str method).
b) The ForeignKey field is the link between two models (oneToOne). A ManyToMany link exists also with the ManyToManyField field (see https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/)
c) Normally: yes. The example I propose may need you to write on a different way the validation you already developed.

Making a fairly complex Django model method sortable in admin?

I have a reasonably complex custom Django model method. It's visible in the admin interface, and I would now like to make it sortable in the admin interface too.
I've added admin_order_field as recommended in this previous question, but I don't fully understand what else I need to do.
class Book(models.Model):
id = models.IntegerField(primary_key=True)
title = models.CharField(max_length=200)
library_id = models.CharField(max_length=200, unique=True)
def current_owner(self):
latest_transaction = Transaction.objects.filter(book=self)[:1]
if latest_transaction:
if latest_transaction[0].transaction_type==0:
return latest_transaction[0].user.windows_id
return None
current_owner.admin_order_field = 'current_owner'
Currently, when I click on the current_owner field in the admin interface, Django gives me
FieldError at /admin/books/book/
Cannot resolve keyword 'current_owner' into field
Do I need to make a BookManager too? If so, what code should I use? This isn't a simple Count like the example in the previous question, so help would be appreciated :)
Thanks!
The Django admin won't order models by the result of a method or any other property that isn't a model field (i.e. a database column). The ordering must be done in the database query, to keep things simple and efficient.
The purpose of admin_order_field is to equate the ordering of a non-field property to the ordering of something that is a field.
For example, a valid values current_owner.admin_order_field could be id, title or library_id. Obviously none of these makes sense for your purpose.
One solution would be to denormalise and always store current_owner as a model field on Book; this could be done automatically using a signal.
You can't do this. admin_order_field has to be a field, not a method - it's meant for when you have a method that returns a custom representation of an underlying field, not when you do dynamic calculations to provide the value. Django's admin uses the ORM for sorting, and that can't sort on custom methods.