i made my own custom analyzer,
I am using elasticsearch:7.5.2
when i run python manage.py search_index --rebuild
the error is
raise RedeclaredFieldError(
django_elasticsearch_dsl.exceptions.RedeclaredFieldError: You cannot redeclare the field named 'name' on CarDocument
class CarDocument(Document):
name = fields.TextField(analyzer=ngram_analyzer)
class Index:
name = 'cars'
settings = {
'number_of_shards': 1,
'number_of_replicas': 0,
}
class Django:
model = Car
fields = [
'name'
]```
Related
I'm using Django 2.2.5 and have multiple choice fields based on enums in my models. For an unknown reason I now get a migration error when using an enum for choice field during migration:
django.db.utils.OperationalError: (1067, "Invalid default value for 'protocol'")
model.py
from django.db import models
# See class above
from .utils import NetworkProtocolList
class Networks(models.Model):
ipv4 = models.GenericIPAddressField(blank=False, null=False)
protocol = models.CharField(choices=NetworkProtocolList.choices(), max_length=20,default=NetworkProtocolList.ETH)
class Meta:
managed = True
db_table = 'networks'
utils.py
from enum import Enum
class NetworkProtocolList(Enum):
ETH = 'Ethernet'
MPLS = 'MPLS'
#classmethod
def choices(cls):
return [(key.name, key.value) for key in cls]
I issued
manage.py makemigrations
and subsequent
manage.py migrate
generated the following error:
django.db.utils.OperationalError: (1067, "Invalid default value for
'protocol'")
xxxx_auto_xxxxxxxx_xxxx.py
# Auto generated migration file
import my_.utils
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('my_app', 'yyyy_auto_yyyyyyyy_yyyy'),
]
operations = [
migrations.AddField(
model_name='networks',
name='protocol',
# Field definition here, pay attention to the default value
field=models.CharField(choices=[('ETH', 'Ethernet'), ('MPLS', 'MPLS')], default=my_app.utils.NetworkProtocolList('Ethernet'), max_length=20),
),
]
Than I edited migration file to manually set the default to a string instead of calling enum class:
xxxx_auto_xxxxxxxx_xxxx.py
# Edited migration file
import my_.utils
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('my_app', 'yyyy_auto_yyyyyyyy_yyyy'),
]
operations = [
migrations.AddField(
model_name='networks',
name='protocol',
# Field definition here, pay attention to the modified default value
field=models.CharField(choices=[('ETH', 'Ethernet'), ('MPLS', 'MPLS')], default='Ethernet', max_length=20),
),
]
Now migration works properly but I wonder why I can't define default value like before using the enum instead of a litteral string, because I have other model field for whom this has worked properly.
Is that a bug, what am I lissing here, How to set default value for a model field based on enum in Django?
Since you are using Django<3.X, Django isn't able to identify the enum value. So, use the .value property of enum class as
protocol = models.CharField(
choices=NetworkProtocolList.choices(),
max_length=20,
default=NetworkProtocolList.ETH.value # <--- change is here
)
I have geojson data in the URL. Here is the URL:
https://publoccityhealthdata.s3.us-east-2.amazonaws.com/chi_boundries.geojson
I need to generate model class for Django using ogrinspect
from django.contrib.gis.db import models
Step 1: Go to manage.py folder level.
Step 2: Make sure django-contrib-gis is installed.
Step 3: Type this command to the terminal python manage.py ogrinspect https://publoccityhealthdata.s3.us-east-2.amazonaws.com/chi_boundries.geojson Neighborhoods --srid=4326 --mapping --multi
You will get following result:
class Neighborhoods(models.Model):
pri_neigh = models.CharField(max_length=0)
sec_neigh = models.CharField(max_length=0)
shape_area = models.CharField(max_length=0)
shape_len = models.CharField(max_length=0)
geom = models.MultiPolygonField(srid=4326)
# This is an auto-generated Django model module created by ogrinspect.
from django.contrib.gis.db import models
neighborhoods_mapping = {
'pri_neigh': 'pri_neigh',
'sec_neigh': 'sec_neigh',
'shape_area': 'shape_area',
'shape_len': 'shape_len',
'geom': 'MULTIPOLYGON',
}
I am creating a project in django using postgresql database. When I run my server the page returns the error
relation "backtest_trade" does not exist
LINE 1: INSERT INTO "backtest_trade" ("pos", "neg", "profit", "trans...
when i try to save my model in the database using back.save(), where back is a variable of the model. I have registered the model in models.py of my app.
I understand that there is no table being created in the database but my understanding is that admin.register should do it. I tried looking up but none of the questions asked was able to help me.
from django.contrib import admin
from django.db import models
from django.contrib.postgres.fields import ArrayField
# Create your models here.
class trade(models.Model):
pos = models.IntegerField(default = 0)
neg = models.IntegerField(default = 0)
profit = models.IntegerField(default = 0)
transaction = ArrayField(models.DecimalField(decimal_places = 3, max_digits= 9,default= 0), default = list)
investment = ArrayField(models.DecimalField(decimal_places = 3, max_digits= 9,default = 0), default = list)
sell = ArrayField(models.DecimalField(decimal_places = 3, max_digits= 9, default = 0), default = list)
entry_date = ArrayField(models.CharField(max_length = 20, default=''), default = list )
exit_date = ArrayField(models.CharField(max_length = 20, default = ''),default = list)
name = models.CharField(max_length = 100, default = "hello")
admin.site.register(trade)
EDIT: I have tried running makemigrations and migrate
I found my error. I had to migrate the particular app in which my model was present.
After running
python manage.py makemigrations backtest
where backtest is the app, I got some error but the table was created in the database
I am creating my a document having a field as EmbeddedDocument using mongoengine.
But I am getting the following error :
AttributeError: 'EmbeddedDocument' object has no attribute '_is_document'
Doing some reasearch I found that the code of mongoengine is written in python 2 and do make it work properly install it using pip3. Did the same still not working.
class DataImportNodeInfo(EmbeddedDocument):
provider_id = fields.IntField(required=False)
carrier_name = fields.StringField(required=False)
basepath = fields.StringField(required=False)
log_tobe_imported = fields.ListField(required=False)
class DataImportConnectionInfo(EmbeddedDocument):
host = fields.StringField(required=True)
user_login = fields.StringField(required=False)
user_pwd = fields.StringField(required=False)
class DataImportNode(DynamicDocument):
# Meta variables
meta = {
'collection': str(KonnectDAConstants.DATA_IMPORT_NODES)
}
cmd = fields.StringField(required=True)
import_source = fields.StringField(required=True)
import_type = fields.StringField(required=True)
active = fields.BooleanField(required=True)
info = fields.EmbeddedDocument(DataImportNodeInfo, required=True)
connection = fields.EmbeddedDocument(DataImportConnectionInfo, required=True)
AttributeError: 'EmbeddedDocument' object has no attribute '_is_document'
You should use EmbeddedDocumentField instead of EmbeddedDocument in DataImportNode:
info = fields.EmbeddedDocumentField(DataImportNodeInfo, required=True)
connection = fields.EmbeddedDocumentField(DataImportConnectionInfo, required=True)
Since the EmbeddedDocumentField is used to reference the EmbeddedDocument.
I have simple models like:
class Car(models.Model):
name = models.CharField()
type = models.ForeignKey(CarTypes)
class CarTypes(models.Model):
type_name = models.CharField()
and serializers:
class CarSerializer(serializers.ModelSerializer):
class Meta:
model = Car
depth = 1
class CarTypeSerializer(serializers.ModelSerializer):
class Meta:
model = CarType
DRF send list of all Car Types to my frontend/angular app which looks like:
car_types = [
{
'id': 1,
'type_name': 'Sedan'
},
{
'id': 2,
'type_name': 'Hatchback'
}
]
I am using Car data in angular form i.e administrator would like to change data about car
<form>
<input ng-model="car.name" type="text" />
<select ng-model="car.type"
ng-options="type.type_name for type in car_types track by type.id"
name="car_type">
</select>
</form>
After submit this form angular send POST to django app which looks like:
{
'id': 1,
'name': 'Audi',
'type': {
'id': 1,
'type_name': 'Sedan'
}
}
PROBLEM
This is case when i am updating Car data.
If i change car type in selectbox my DRF serializer will change name from Sedan to i.e Hatchback instead of ascribe whole object. So Car Type Sedan will be destroyed and replaced.
New Car types will looks like:
car_types = [
{
'id': 1,
'type_name': 'Hatchback'
},
{
'id': 2,
'type_name': 'Hatchback'
}
]
(Angular send correct dict with id and name. DRF accessing only name instead of id and name to car.type)
QUESTIONS
How should I serialize and deserialize data with FK ? As a PrimaryKey then in angular connect those Primary Keys with names ? I like using depth options because i received whole dict
Maybe there is function in DRF to change data before validation which allow me to change received DICT to PK ?