Wednesday, 1 August 2018

Purpose of django.db.models.fields.Field.name argument

Recently i discovered that there is not-documented django.db.models.fields.Field.name option:

@total_ordering
class Field(RegisterLookupMixin):  #   here we have it
    ...                                   ↓↓↓↓↓↓↓↓↓
    def __init__(self, verbose_name=None, name=None, primary_key=False,
                 max_length=None, unique=False, blank=False, null=False,
                 db_index=False, rel=None, default=NOT_PROVIDED, editable=True,
                 serialize=True, unique_for_date=None, unique_for_month=None,
                 unique_for_year=None, choices=None, help_text='', db_column=None,
                 db_tablespace=None, auto_created=False, validators=(),
                 error_messages=None):
        ...

There is mention of it in doc-way:

# A guide to Field parameters:
#
#   * name:      The name of the field specified in the model.
#   * attname:   The attribute to use on the model object. This is the same as
#                "name", except in the case of ForeignKeys, where "_id" is
#                appended.
#   * db_column: The db_column specified in the model (or None).
#   * column:    The database column for this field. This is the same as
#                "attname", except if db_column is specified.
#
# Code that introspects values, or does other dynamic things, should use
# attname. For example, this gets the primary key value of object "obj":
#
#     getattr(obj, opts.pk.attname)

Description above is related with #683 ([patch] Saving with custom db_column fails) ticket.

So if we look through whole django.db.models.fields.Field class, this seems as name option is setting attribute name, which make real name of variable invalid:

Suppose we have our model:

# models.py
from django.db import models


class SomeModel(models.Model):
    first = models.CharField(max_length=50, verbose_name='first', name='second')
    third = models.CharField(max_length=50, verbose_name='third')

What django-admin shell tells us:

In[2]: from app.models import SomeModel
In[3]: SomeModel.objects.create(first='first', third='third')
Traceback (most recent call last):
  File "/Users/ailove/Home/personal/untitled/venv/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-3-08e446dfd6e3>", line 1, in <module>
    SomeModel.objects.create(first='first', third='third')
  File "/Users/ailove/Home/personal/untitled/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/ailove/Home/personal/untitled/venv/lib/python3.6/site-packages/django/db/models/query.py", line 415, in create
    obj = self.model(**kwargs)
  File "/Users/ailove/Home/personal/untitled/venv/lib/python3.6/site-packages/django/db/models/base.py", line 495, in __init__
    raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg)
TypeError: 'first' is an invalid keyword argument for this function
In[4]: obj = SomeModel.objects.create(second='second', third='third')
In[5] obj.third
Out[5]: 'third'
In[6]: obj.second
Out[6]: 'second'
In[7]: obj.first
Traceback (most recent call last):
  File "/Users/ailove/Home/personal/untitled/venv/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-7-f0deaec10795>", line 1, in <module>
    obj.first
AttributeError: 'SomeModel' object has no attribute 'first'

Question is kinda broad, but i am also curious.

Is this name option is a thing that only helped to develop django, or ordinary developers can also make use of it? And if we can, what for?



from Purpose of django.db.models.fields.Field.name argument

No comments:

Post a Comment