Naming Convention for fields of a model in django - django

What are some naming convention for fields of a model in django. My problem is I am getting an error
django.core.exceptions.ImproperlyConfigured: Field name `tutor1` is not valid for model `ClientEntry`
Is using integers in a field name is just wrong? What are my options to name it in number like tutor1, tutor2, tutor3? I also tried tutor_1 but got the same error.
Note: tutor1 postgres ArrayField
EDIT: here is the traceback
Traceback (most recent call last):
File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/rest_framework/viewsets.py", line 103, in view
return self.dispatch(request, *args, **kwargs)
File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/rest_framework/views.py", line 483, in dispatch
response = self.handle_exception(exc)
File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/rest_framework/views.py", line 443, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/rest_framework/views.py", line 480, in dispatch
response = handler(request, *args, **kwargs)
File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/rest_framework/mixins.py", line 20, in create
serializer.is_valid(raise_exception=True)
File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/rest_framework/serializers.py", line 236, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/rest_framework/serializers.py", line 434, in run_validation
value = self.to_internal_value(data)
File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/rest_framework/serializers.py", line 482, in to_internal_value
fields = self._writable_fields
File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/django/utils/functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/rest_framework/serializers.py", line 370, in _writable_fields
field for field in self.fields.values() if not field.read_only
File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/rest_framework/serializers.py", line 363, in fields
for key, value in self.get_fields().items():
File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/rest_framework/serializers.py", line 1045, in get_fields
source, info, model, depth
File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/rest_framework/serializers.py", line 1190, in build_field
return self.build_unknown_field(field_name, model_class)
File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/rest_framework/serializers.py", line 1302, in build_unknown_field
(field_name, model_class.__name__)
django.core.exceptions.ImproperlyConfigured: Field name `amount_paid_tutor1` is not valid for model `ClientEntry`.
here is relevant field
amount_paid_to_tutor1 = ArrayField(
models.IntegerField(
blank=True
),
blank=True,
null=True
)
Serializer is basically all the fields and views are this
class ClientEntryViewSet(viewsets.ModelViewSet):
queryset = ClientEntry.objects.all()
serializer_class = ClientEntrySerializer

It seems like you have amount_paid_to_tutor1 field on your model, but error occurred because of amount_paid_tutor1. Find amount_paid_tutor1 and change to amount_paid_to_tutor1.

Related

AttributeError: 'Serializer' object has no attribute '_meta'

i have created this serializer to validate on the presence of a record with these column combination`
class CampaignServicesValidation(serializers.Serializer):
campaign_id = serializers.IntegerField(required=True)
service_id = serializers.IntegerField(required=True)
def validate(self, data):
try:
campaign_service = CampaignServices.objects.get(campaign_id=data['campaign_id'],
service_id=data['service_id'])
print("found"+str(campaign_service.id))
except Exception:
raise serializers.ValidationError(detail='Campaign Service does not exist')
return campaign_service
and it is called in my viewSet like this:
campaign_service = CampaignServicesValidation(data={'campaign_id': request.data['campaign_id'], 'service_id': pk})
if not campaign_service.is_valid():
return RestResponse(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, serializer_error=campaign_service.errors)
when the combination is not found it raises an exception and works well, but when it passes validation and enters the is_valid() function in the if condition it produces this error
Traceback (most recent call last):
File "D:\RightsHero\collector-management\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "D:\RightsHero\collector-management\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\RightsHero\collector-management\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "D:\RightsHero\collector-management\collectors_management\views.py", line 157, in update_campaign_service_frequency
serializer.save()
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\serializers.py", line 207, in save
self.instance = self.update(self.instance, validated_data)
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\serializers.py", line 993, in update
info = model_meta.get_field_info(instance)
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\utils\model_meta.py", line 35, in get_field_info
opts = model._meta.concrete_model._meta
AttributeError: 'CampaignServicesValidation' object has no attribute '_meta'
I have tried changing serializer.Serializer to ModelSerialzier but nothing changed
Since Serializer does not have a _meta attribute, it does not have the is_valid() method. Instead, you should check the serializer.errors attribute of the serializer after calling validate().

Query inherited models

I have 3 Models:
Actor(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
type = models.Charfield(max_length=20)
Organisation(Actor):
name = models.Charfield(max_length=20)
actor = models.OneToOneField(Actor, on_delete=Models.CASCADE)
parent_organisation = models.ForeignKey(Actor, on_delete=models.CASCADE)
CustomUser(AbstractBaseUser,PermissionsMixin,Actor):
name = models.Charfield(max_length=20)
member_of = models.ManyToManyField(Actor, on_delete=models.CASCADE)
I am basically trying to get all users within an organisation:
User and Organisation share a common named id - Actor and Inherit from this class.
I have tried:
user_list = CustomerUser.objects.filter(parent__parent__id=request.session['organisation']
and
user_list = Organisation.objects.filter(parent__parent_user_organisation=request.session[''organisation']
and
user_list = Actor.objects.filter(parent__parent__user_organisation__in=request.session['organisation'])
although I would like to try and keep all queries on the actor model if possible. Eventually, id like to get all users within a multi-tiered organisation structure although for now, I'm happy to get just users based on Organisation_parent rather than ----- Organisation_parent_Organisation_parent etc...
I have changed my model structure to inherited to try and make queries easier but not having much luck.
The full trace:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-
packages/django/db/models/fields/__init__.py", line 2348, in to_python
return uuid.UUID(**{input_form: value})
File "/usr/local/lib/python3.8/uuid.py", line 171, in __init__
raise ValueError('badly formed hexadecimal UUID string')
During handling of the above exception (badly formed hexadecimal UUID string), another exception occurred: File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/src/app/administration/views.py", line 133, in user_list
user_list = Actor.objects.filter(parent__parent__user_organisation__in=request.session['organisation']) File "/usr/local/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs)) File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1350, in add_q
clause, _ = self._add_q(q_object, self.used_aliases) File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter( File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1311, in build_filter
condition = self.build_lookup(lookups, col, value) File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1165, in build_lookup
lookup = lookup_class(lhs, rhs) File "/usr/local/lib/python3.8/site-packages/django/db/models/lookups.py", line 22, in __init__
self.rhs = self.get_prep_lookup() File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/related_lookups.py", line 59, in get_prep_lookup
self.rhs = [target_field.get_prep_value(v) for v in self.rhs] File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/related_lookups.py", line 59, in <listcomp>
self.rhs = [target_field.get_prep_value(v) for v in self.rhs] File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/related.py", line 945, in get_prep_value
return self.target_field.get_prep_value(value) File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2332, in get_prep_value
return self.to_python(value) File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2350, in to_python
raise exceptions.ValidationError(
Exception Type: ValidationError at /administration/administration/user/list Exception Value: ['“4” is not a valid UUID.']

combining __startswith and __in not working

I have a QuerySet and an array of strings that I want to test against the QuerySet.
The problem is the values I want to check are foreignKeys and the important characters of the foreignKey are in the beginning.
The query I thought would work is this:
materials_comparison_list.extend(materials_non_eu.filter(code__code__startswith__in=headings_list))
materials_non_eu is the QuerySet, headings_list is the array
However when running that it returns the following error:
django.core.exceptions.FieldError: Unsupported lookup 'startswith' for CharField or join on the field not permitted, perhaps you meant startswith or istartswith
I tried to change the place or __startswith and __in but that produces the same error (different words)
The models for materials looks like this:
class Materials(models.Model):
id = models.AutoField(primary_key=True)
row = models.IntegerField(null=True)
code = models.ForeignKey('HS_code', on_delete=models.CASCADE, null=True)
...
The model for the code looks like this:
class HS_Code(models.Model):
id = models.AutoField(primary_key=True)
code = models.CharField(max_length=10, unique=False)
....
The complete console output:
Traceback (most recent call last):
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/rest_framework/views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/rest_framework/views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
raise exc
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/rest_framework/views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/rest_framework/decorators.py", line 50, in handler
return func(*args, **kwargs)
File "/Users/5knnbdwm/Python_env/FlexOrigin/main/user.py", line 1115, in api_user_summary_v2
print(Calculation_Master(
File "/Users/5knnbdwm/Python_env/FlexOrigin/main/cluster_v2.py", line 60, in Calculation_Master
MAXNOM(session, materials, country, rule_block[1])
File "/Users/5knnbdwm/Python_env/FlexOrigin/main/cluster_v2.py", line 140, in MAXNOM
materials_comparison_list.extend(materials_non_eu.filter(
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/models/query.py", line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/models/query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1350, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1311, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1150, in build_lookup
lhs = self.try_transform(lhs, name)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1198, in try_transform
raise FieldError(
django.core.exceptions.FieldError: Unsupported lookup 'startswith' for CharField or join on the field not permitted, perhaps you meant startswith or istartswith?
You can not combine the two, but you can make a disjunctive filter with a Q object:
from django.db.models import Q
materials_comparison_list.extend(
materials_non_eu.filter(Q(
*[('code__code__startswith', heading) for heading in headings_list],
_connector=Q.OR
))
)

Django get_or_create ValueError

Trying to add rows from a DataFrame into Django model.
models.py:
class CreditIndex_TEST(models.Model):
loanBook = models.ForeignKey(LoanBooks, on_delete=models.CASCADE)
run_date = models.DateField()
index_date = models.DateField()
index_CD = models.IntegerField()
Index_value = models.FloatField()
class Meta:
constraints = [
models.UniqueConstraint(fields= ['loanBook','run_date','index_date','index_CD'], name='unique_CreditIndexPair')
]
views.py:
for index, row in tempDf.iterrows():
obj, created = CreditIndex_TEST.objects.get_or_create(
loanBook=dbname,
run_date= run_date,
index_date=row['Date'],
index_CD=1,
Index_value=row['CreditIndex_CD1']
)
ERROR::
ValueError: Field 'id' expected a number but got 'Botswana_TU'.
I don't understand why I am being asked to specify id. The record I am trying to add to the model does not exist and therefore Django should create it and assign id, not expect it from me?
EDIT (full traceback):
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/gunthermarais/credit-risk/django/RiskLab/Provisions/views.py", line 48, in macroGUI
Index_value=row['CreditIndex_CD1']
File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 575, in update_or_create
obj = self.select_for_update().get(**kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 404, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1350, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1381, in _add_q
check_filterable=check_filterable,
File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1311, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1165, in build_lookup
lookup = lookup_class(lhs, rhs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/lookups.py", line 22, in __init__
self.rhs = self.get_prep_lookup()
File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/related_lookups.py", line 115, in get_prep_lookup
self.rhs = target_field.get_prep_value(self.rhs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1776, in get_prep_value
) from e
ValueError: Field 'id' expected a number but got 'Botswana_TU'.

What is '_get_val_from_obj' mechanic does?

I am new to tooling job. Currently my favorite package in Django is outdated and seems no one care by now. Therefore I would like to study it.
Problem:
https://github.com/philippbosch/django-geoposition/issues/100
Traceback (most recent call last):
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/sarit/.pyenv/versions/3.6.4/lib/python3.6/contextlib.py", line 52, in inner
return func(*args, **kwds)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/viewsets.py", line 95, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/views.py", line 494, in dispatch
response = self.handle_exception(exc)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/views.py", line 454, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/views.py", line 491, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/mixins.py", line 22, in create
headers = self.get_success_headers(serializer.data)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/serializers.py", line 537, in data
ret = super(Serializer, self).data
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/serializers.py", line 504, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/fields.py", line 1858, in to_representation
return self.model_field.value_to_string(obj)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/src/django-geoposition/geoposition/fields.py", line 50, in value_to_string
value = self._get_val_from_obj(obj)
AttributeError: 'GeopositionField' object has no attribute '_get_val_from_obj'
Official Docs:
https://docs.djangoproject.com/en/2.0/releases/2.0/
Field._get_val_from_obj() is removed.
Question:
How to solve this error?
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return smart_text(value)
Update:
https://github.com/pennersr/django-allauth/issues/1865
#linaskilius says
Django recommends using the Field.value_from_object() instead.
My Fork:
https://github.com/elcolie/django-geoposition