Related
I am trying to call a get api but it gives me this error everytime.
The error:
AttributeError: Got AttributeError when attempting to get a value for field name on serializer NestedSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the int instance.
Original exception text was: 'int' object has no attribute 'name'.
My models:
class Destination(models.Model):
Continent_Name = (
('Europe', 'Europe',),
('Asia', 'Asia',),
('North America', 'North America',),
('South America', 'South America',),
('Africa', 'Africa',),
('Oceania', 'Oceania',),
('Polar', 'Polar',),
('Regions', 'Regions',),
)
name = models.CharField(max_length=255, unique=True)
continent = models.CharField(max_length=255, choices=Continent_Name, default='Europe')
top = models.BooleanField(default=False)
dest_image = models.ImageField(blank=True)
def __str__(self):
return self.name
class Package(models.Model):
TOUR_TYPE = (
('Custom-made trip with guide and/or driver', 'Custom-made trip with guide and/or driver',),
('Custom-made trip without guide and driver', 'Custom-made trip without guide and driver',),
('Group Tour', 'Group Tour',),
('Cruise Tour', 'Cruise Tour',),
)
operator = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
destination = models.ForeignKey(Destination, on_delete=models.CASCADE)
package_name = models.CharField(max_length=255)
city = models.CharField(max_length=255)
featured = models.BooleanField(default=False)
price = models.IntegerField(verbose_name="Price in Nrs")
price_2 = models.IntegerField(verbose_name="Price in $")
duration = models.IntegerField(default=5)
duration_hours = models.PositiveIntegerField(blank=True,null=True,verbose_name="Hours If One day Tour")
discount = models.IntegerField(verbose_name="Discount %", default=15)
#discounted_price = models.IntegerField(default=230)
#savings = models.IntegerField(default=230)
tour_type = models.CharField(max_length=100, choices=TOUR_TYPE, default='Group Tour')
new_activity = models.ManyToManyField(NewActivity)
accommodation = models.CharField(max_length=255, default='Guest House & Hotel')
transport = models.CharField(max_length=150, default='Flight')
age_range = models.CharField(max_length=100, default='6 to 79 years old')
fix_departure = models.BooleanField(default=False)
rating = models.IntegerField(choices=((1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 5))
)
image = models.ImageField(blank=True, verbose_name="Thumbnail Image-Vertical")
content =RichTextField()
highlights = RichTextField()
inclusions = RichTextField()
exclusions = RichTextField()
# itinerary = models.ManyToManyField(Itinerary)
itinerary_text = RichTextField()
faqs = RichTextField(blank=True)
image_1= models.ImageField(blank=True,null = True,verbose_name="Image-Horizontal")
image_2= models.ImageField(blank=True,null = True,verbose_name="Image-Square")
image_3= models.ImageField(blank=True,null = True,verbose_name="Image-Sqaure")
date_created = models.DateField()
def __str__(self):
return self.package_name
My views:
class PackageSearchAPi(ListAPIView):
queryset = Package.objects.all().order_by('package_name')
serializer_class = PackageSerializer
def get(self, request, *args, **kwargs):
search = self.request.query_params.get('search',None)
if search is not None:
qs = Package.objects.filter(Q(destination__name__icontains=search)|
Q(destination__continent__icontains=search)|
Q(package_name__icontains=search)|
Q(city__icontains=search)).disctinct()
else:
qs = Package.objects.values('id','destination','package_name','city')
serializer = PackageSerializer(qs,many=True)
return Response(serializer.data,status=200)
My serializers:
class PackageSerializer(serializers.ModelSerializer):
class Meta:
model = Package
fields = ['id', 'operator','destination', 'package_name', 'duration', 'featured', 'price','price_2', 'discount',
'city', 'tour_type','new_activity', 'accommodation', 'transport', 'age_range',
'fix_departure', 'rating', 'image', 'date_created', ]
depth = 1
Here I checked the code and nothing seems to be wrong in any part but keeps getting the same above error.
Traceback:
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\Saroj\Desktop\TravelCRM\apps\packages\views.py", line 251, in get
return Response(serializer.data,status=200)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 760, in data
ret = super().data
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 260, in data
self._data = self.to_representation(self.instance)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 677, in to_representation
return [
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 678, in <listcomp>
self.child.to_representation(item) for item in iterable
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 529, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 516, in to_representation
attribute = field.get_attribute(instance)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\fields.py", line 487, in get_attribute
raise type(exc)(msg)
AttributeError: Got AttributeError when attempting to get a value for field `name` on serializer `NestedSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `int` instance.
Original exception text was: 'int' object has no attribute 'name'.
For nested relations you have to define nested serializer
class DestinationSerializer(serializers.Serializer):
name = serializers.CharField()
top = serializers.BooleanField()
continent = serializers.CharField()
class PackageSerializer(serializers.ModelSerializer):
destination = DestinationSerializer()
class Meta:
model = Package
fields = ['id', 'operator','destination', 'package_name', 'duration', 'featured', 'price','price_2', 'discount',
'city', 'tour_type','new_activity', 'accommodation', 'transport', 'age_range',
'fix_departure', 'rating', 'image', 'date_created', ]
Whenever i try to save an object that has a nested field i get a Type error.
TypeError: isinstance() arg 2 must be a type or tuple of types
I have following document classes:
class CreationIndex(InnerDoc):
created_by = Keyword()
created_date = Date()
class UpdationIndex(InnerDoc):
updated_by = Keyword()
updated_date = Date()
class IndustryIndex(DocType):
name = Text(analyzer= 'english')
creation = CreationIndex()
updation = Nested(UpdationIndex())
class Meta:
index = 'industry'
def bulk_indexing():
elastic_connection = Elasticsearch(hosts=['localhost'], timeout=20)
if elastic_connection.indices.exists('industry'):
elastic_connection.indices.delete('industry')
if elastic_connection.indices.exists('category'):
elastic_connection.indices.delete('category')
IndustryIndex.init()
print('HI')
bulk(client=elastic_connection, actions=(b.indexing() for b in models.Industry.objects.all()))
My Industry Model is a django model (where i have used mongoDB so itself is a dynamic document) which is defined as
class Industry(DynamicDocument,BaseCreationUpdation):
name=StringField(required=True,unique=True)
def save(self,*args,**kwargs):
'''
'''
self=save_created_updated_info(self)
super(Industry,self).save(args,kwargs)
def indexing(self):
objCreation = CreationIndex(
created_by = self.creation.created_by,
created_date = self.creation.created_date.date().isoformat()
)
print(objCreation.to_dict())
obj = IndustryIndex(
meta = {'id': str(self.id)},
name = self.name,
creation = objCreation.to_dict(),
updation = [],
)
for objUp in self.updation:
objUpdation = UpdationIndex(
updated_by = objUp.updated_by,
updated_date = objUp.updated_date.date().isoformat()
)
print(objUpdation)
obj.updation.append(objUpdation)
print()
print(obj.to_dict())
print()
obj.save()
return obj.to_dict(include_meta=True)
#classmethod
def index_document(cls,sender, document, **kwargs):
document.indexing()
Now whenever i run the bulk_indexing module it comes up with a problem :
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "D:\projects\django\bhetincha\category\search.py", line 57, in bulk_indexing
bulk(client=elastic_connection, actions=(b.indexing() for b in models.Industry.objects.all()))
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch\helpers\__init__.py", line 257, in bulk
for ok, item in streaming_bulk(client, actions, **kwargs):
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch\helpers\__init__.py", line 180, in streaming_bulk
client.transport.serializer):
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch\helpers\__init__.py", line 58, in _chunk_actions
for action, data in actions:
File "D:\projects\django\bhetincha\category\search.py", line 57, in <genexpr>
bulk(client=elastic_connection, actions=(b.indexing() for b in models.Industry.objects.all()))
File "D:\projects\django\bhetincha\category\models.py", line 80, in indexing
obj.save()
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch_dsl\document.py", line 405, in save
self.full_clean()
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch_dsl\utils.py", line 417, in full_clean
self.clean_fields()
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch_dsl\utils.py", line 403, in clean_fields
data = field.clean(data)
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch_dsl\field.py", line 179, in clean
data = super(Object, self).clean(data)
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch_dsl\field.py", line 90, in clean
data = self.deserialize(data)
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch_dsl\field.py", line 81, in deserialize
for d in data
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch_dsl\field.py", line 81, in <listcomp>
for d in data
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch_dsl\field.py", line 160, in _deserialize
if isinstance(data, self._doc_class):
TypeError: isinstance() arg 2 must be a type or tuple of types
Why is there this error? When i removed the updation filed which is nested it all works, though the creation field is the same. Whats the problem here?
The way you are initialising the nested field is wrong - you need to pass a class rather than an instance of the class as the argument to the constructor (i.e., drop the brackets):
updation = Nested(UpdationIndex) # Instead of Nested(UpdationIndex())
I'm advancing with the web app I asked about earlier.
Currently, my models.py is
from django.db import models
from unittest.util import _MAX_LENGTH
class Alimento(models.Model):
INTOLERANCIAS = (
('00', 'Ninguna'),
('GL', 'Gluten'),
('CR', 'Crustáceos'),
('HU', 'Huevos'),
('FS', 'Frutos Secos'),
('AP', 'Apio'),
('MO', 'Mostaza'),
('SE', 'Sésamo'),
('PE', 'Pescado'),
('CA', 'Cacahuetes'),
('SO', 'Sulfitos'),
('SJ', 'Soja'),
('LA', 'Lácteos'),
('AL', 'Altramuz'),
('ML', 'Moluscos'),
('CA', 'Cacao'),
)
nombre = models.CharField(max_length=60)
intolerancia = models.CharField(max_length=2, choices=INTOLERANCIAS)
def __str__(self):
return self.nombre
class Receta(models.Model):
nombre = models.CharField(max_length=100)
raciones = models.IntegerField(default=1)
preparacion = models.TextField(default='')
consejos = models.TextField(blank=True)
ingredientes = models.ManyToManyField(Alimento, through='Ingrediente', related_name='ingredientes')
def __str__(self):
return self.nombre
def getIntolerancias(self):
ing = self.ingredientes.all()
intolerancias = []
for i in ing:
alimentos = i.alimento.all()
for a in alimentos:
intolerancias.append(a.get_intolerancia_display())
return intolerancias
class Ingrediente(models.Model):
receta = models.ForeignKey('recetas.Receta', on_delete=models.CASCADE)
alimento = models.ManyToManyField(Alimento)
cantidad = models.FloatField(default=0)
descripcion = models.CharField(max_length=60, blank=True)
def __str__(self):
return self.alimento.__str__()
the method getIntolerancias is supposed to list the food intolerances related to each of the ingredients of a given recipe (Receta). To do that, I try to get the queryset of ingredients (Ingrediente) with ing = self.ingredientes, but when I try it on shell I get this error message
Traceback (most recent call last): File "/usr/lib/python3.5/code.py", line 91, in runcode
exec(code, self.locals) File "<console>", line 1, in <module> File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 476, in __get__
return self.related_manager_cls(instance) File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 758, in __init__
self.target_field_name = rel.field.m2m_reverse_field_name() File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 15, in _curried
return _curried_func(*(args + moreargs), **dict(kwargs, **morekwargs)) File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related.py", line 1504, in _get_m2m_reverse_attr
return getattr(self, cache_attr) AttributeError: 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache'
I've searched for the error, but the answers I've found don't seem to have what I need (I may just don't understand enough to see it does?)
UPDATE
When I run this on the shell I do
g = Receta.objects.get(nombre = 'Gazpacho')
g.getIntolerancias()
I get an error
intolerancias.append(a.get_intolerancia_display()) AttributeError:
'Ingrediente' object has no attribute 'get_intolerancia_display'
However, if I iterate and get the first element of g.ingredientes.all() and call get_intolerancia_display() it does work OK
a = g.ingredientes.all().first()
a.get_intolerancia_display()
'Gluten'
Update after comments:
Documentation about Many-to-many relation
def get_intolerancias(self):
alimentos = self.ingredientes.all() # Give us all alimento of a recetta
intolerancias = []
for a in alimentos:
intolerancias.append(a.get_intolerancia_display())
return intolerancias
I'm facing the problem when creating the many to many relation with through model using factory. I followed this link factory recipies.
I'm getting the TypeError: 'datetime.date' object is not callable this error. Help me to find the solution.
I got an another error:
File "/local/lib/python2.7/site-packages/factory/base.py", line 492, in _generate
obj = cls._prepare(create, **attrs)
File "/local/lib/python2.7/site-packages/factory/base.py", line 467, in _prepare
return cls._create(model_class, *args, **kwargs)
File "/local/lib/python2.7/site-packages/factory/django.py", line 174, in _create
return manager.create(*args, **kwargs)
File "/local/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/local/lib/python2.7/site-packages/django/db/models/query.py", line 346, in create
obj = self.model(**kwargs)
File "/local/lib/python2.7/site-packages/django/db/models/base.py", line 480, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'a1' is an invalid keyword argument for this function
models.py
class TimeStampModel(models.Model):
start_date = models.DateField(_('Start Date'))
end_date = models.DateField(_('End Date'))
class Meta:
abstract = True
class User(models.Model):
name = models.CharField()
class Aclass(models.Model):
name = models.CharField()
user = models.ForeignKey(User)
report = models.ManyToManyField('self', through='Bcalss')
class Bcalss(TimeStampModel):
a1 = models.ForeignKey(Aclass)
b1 = models.ForeignKey(Aclass)
factories.py
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.User
name = "John Doe"
class AclassFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Aclass
user = factory.SubFactory(UserFactory)
name = "Admins"
class BclassFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Bclass
a1 = factory.SubFactory(AclassFactory)
b1 = factory.SubFactory(AclassFactory)
start_date = fuzzy.FuzzyDate(timezone.localtime(timezone.now())).date(), timezone.localtime(timezone.now())).date() + timedelta(days=2))
end_date = fuzzy.FuzzyDate(timezone.localtime(timezone.now())).date(), timezone.localtime(timezone.now())).date() + timedelta(days=6))
class AclassWithBclassFactory(AclassFactory):
reports = factory.RelatedFactory(BclassFactory, 'a1')
tests.py
class A1classModelTestCase(TestCase):
def test_a1class_create(self):
a1 = factories.AclassWithBclassFactory.create()
In this line:
start_date = factory.LazyAttribute(datetime.today)
You need to actually call the function with ():
start_date = factory.LazyAttribute(datetime.today())
Anyone can find what is causing the error in my code? I already searched, but didn't find an answer. I think the problem is with the function objects.get(param), but I'm not sure.
What I wanted to do with my code was to retrieve the objects Genre, Country, Language and Directors if they were already added to the database.
Here's the code:
Models.py
from django.db import models
from numpy import unique
class Director(models.Model):
director = models.CharField(max_length=500, unique=True)
def __unicode__(self):
return self.director
def __init__(self, director):
super(Director, self).__init__()
self.director = director
class Language(models.Model):
language = models.CharField(max_length=500, unique=True)
def __unicode__(self):
return self.language
def __init__(self, language):
super(Language, self).__init__()
self.language = language
class Genre(models.Model):
genre = models.CharField(max_length=500, unique=True)
def __unicode__(self):
return self.genre
def __init__(self, genre):
super(Genre, self).__init__()
self.genre = genre
class Country(models.Model):
country = models.CharField(max_length=500, unique=True)
def __unicode__(self):
return self.country
def __init__(self, country):
super(Country, self).__init__()
self.country = country
class Movie(models.Model):
id_movie = models.CharField(max_length=200, unique=True)
rating = models.CharField(max_length=200)
votes = models.CharField(max_length=200)
year = models.CharField(max_length=10)
genre = models.ManyToManyField(Genre)
country = models.ManyToManyField(Country)
language = models.ManyToManyField(Language)
directors = models.ManyToManyField(Director)
def __init__(self, id_movie, rating, votes, year):
super(Movie, self).__init__()
self.id_movie = id_movie
self.rating = rating
self.votes = votes
self.year = year
def __unicode__(self):
return self.id_movie
crawler.py
from movie_info.models import Movie, Genre, Director, Language, Country
def get_movie_info(codigo_do_filme):
import imdb
ia = imdb.IMDb()
movie = ia.get_movie(codigo_do_filme)
return {'titulo': movie['title'], 'rating': movie['rating'], 'votes': movie['votes'], 'ano': movie['year'], 'genero': movie['genre'][0], 'pais': movie['countries'][0], 'idioma': movie['lang'][0], 'directors': movie['director']}
def read_sheet(file_name, fieldnames=None, delimiter=",", quotechar="\n"):
from csv import DictReader
reader = DictReader(open(file_name,'rb'), fieldnames = fieldnames, delimiter = delimiter, quotechar=quotechar)
return reader
def fill_db_movie_info(the_sheet_file):
file_csv = read_sheet(the_sheet_file)
for movie in file_csv:
id_filme = movie['id_move']
if not Movie.objects.filter(id_movie=id_filme).exists():
info = get_movie_info(id_filme)
rating_imdb = info['rating']
movie_votes = info['votes']
movie_year = info['ano']
movie_genre = info['genero']
movie_country = info['pais']
movie_lang = info['idioma']
movie_directors = info['directors']
addToDB = Movie(id_filme, rating_imdb, movie_votes, movie_year)
addToDB.save()
if not Genre.objects.filter(genre=movie_genre).exists():
genreToDB = Genre(movie_genre)
genreToDB.save()
addToDB.genre.add(genreToDB)
else:
addToDB.genre.add(Genre.objects.get(genre=movie_genre))
if not Country.objects.filter(country=movie_country).exists():
countryToDB = Country(movie_country)
countryToDB.save()
addToDB.country.add(countryToDB)
else:
addToDB.country.add(Country.objects.get(country=movie_country))
if not Language.objects.filter(language=movie_lang).exists():
langToDB = Language(movie_lang)
langToDB.save()
addToDB.language.add(langToDB)
else:
addToDB.language.add(Language.objects.get(language=movie_lang))
for m_director in movie_directors:
if not Director.objects.filter(director=m_director['name']).exists():
directorsToDB = Director(m_director['name'])
directorsToDB.save()
addToDB.directors.add(directorsToDB)
else:
addToDB.directors.add(Director.objects.get(director=m_director['name']))
print "salvou: " + id_filme, rating_imdb, movie_votes, movie_year, movie_genre, movie_country, movie_lang, movie_directors[0]
The Traceback:
pydev debugger: starting (pid: 1424)
Traceback (most recent call last):
File "/Applications/eclipse/plugins/org.python.pydev_3.5.0.201405201709/pysrc/pydevd.py", line 1845, in <module>
debugger.run(setup['file'], None, None)
File "/Applications/eclipse/plugins/org.python.pydev_3.5.0.201405201709/pysrc/pydevd.py", line 1373, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/Users/rubenspessoa/Documents/Workspace/LearningDjango/main.py", line 7, in <module>
fill_db_movie_info('/Users/rubenspessoa/Documents/Workspace/DATASET/test_subdataset.csv')
File "/Users/rubenspessoa/Documents/Workspace/LearningDjango/crawler.py", line 49, in fill_db_movie_info
addToDB.country.add(Country.objects.get(country=movie_country))
File "/Library/Python/2.7/site-packages/django/db/models/manager.py", line 151, in get
return self.get_queryset().get(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 304, in get
num = len(clone)
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 77, in __len__
self._fetch_all()
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 857, in _fetch_all
self._result_cache = list(self.iterator())
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 230, in iterator
obj = model(*row_data)
TypeError: __init__() takes exactly 2 arguments (3 given)
You have defined __init__ methods for all your models. You should not do that.