Cannot resolve keyword into field error while using drf model serializer and search_fields within field set? - serialization

SerializerClass:
class VacancySerializer(serializers.ModelSerializer):
organization_small_name = serializers.CharField(source='organization.short_name', read_only=True)
class Meta:
model = Vacancy
fields = ['organization', 'description', 'specs', 'type', 'publication_date',
'is_published', 'withdrawal_data', 'organization_small_name', ]
read_only_fields = ['publication_date', 'is_published', 'withdrawal_data',]
ViewSet:
class VacancyViewSet(viewsets.ModelViewSet):
queryset = Vacancy.objects.all()
serializer_class = VacancySerializer
filter_backends = [filters.SearchFilter]
search_fields = ['organization_small_name']
...
Model:
class Vacancy(models.Model):
organization = models.OneToOneField(DictOrganization, on_delete=models.CASCADE, related_name='vacancies')
description = models.TextField('Описание')
specs = models.ManyToManyField(DictSpec, blank=True)
type = models.CharField('Тип', max_length=20, choices=VacancyType.choices(), default=VacancyType.PRACTICE.value)
publication_date = models.DateField('Дата публикации', null=True, blank=True)
is_published = models.BooleanField('Опубликовано', default=False)
withdrawal_data = models.DateField('Дата снятия с публикации', null=True, blank=True)
My goal is to make API search by 'organization_small_name' field
that is in VacancySerializer.
Server runs successfully, but as soon as i add ?search parameter, i get next error:
Why it doesn't recognize 'organization_small_name' field, even thought it is decribed in serializer, and how can i fix it?

Related

Got AttributeError when attempting to get a value for field `email` on serializer `UserSerializer`

Creating Django REST FRamework API. Using Abstract User and email is the default logging parameter using.
AttributeError at /post/
Got AttributeError when attempting to get a value for field email on serializer UserSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the Post instance.
Original exception text was: 'Post' object has no attribute 'email'.
class PostSerializer(ModelSerializer):
category = ReadOnlyField(source='category.name')
author = UserSerializer(source='user.email')
#question = serializers.CharField(source='question.text', read_only=True)
class Meta:
model = Post
fields = '__all__'
class User(AbstractUser):
username = models.CharField("Username", max_length=50, unique=True)
email = models.EmailField("Email Address", max_length=254, unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name', 'last_name']
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE, to_field='email')
category = models.ForeignKey(Category, related_name='categorys', on_delete=models.CASCADE)
body = models.TextField()
image = models.ImageField(upload_to='blog/%Y/%m/%d', blank=True)
publish = models.DateTimeField(default=timezone.now)
rating = models.IntegerField("Rumor Rate", validators=[MaxValueValidator(5), MinValueValidator(0)], default=1, null=True)
created = models.DateTime[![enter image description here][1]][1]Field(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
I suppose you want to return the author's email in the author field when you request the Post endpoint. You may also convert the author field in the serializer to a ReadOnlyField (as category) and specify source='author.email', since your model foreign key is named like that:
class PostSerializer(ModelSerializer):
category = ReadOnlyField(source='category.name')
author = ReadOnlyField(source='author.email')
# ...

Django Model Design (Big model vs multiple)

I have a question about designing my models. Suppose I have a following model:
class Comment(models.Model):
who = models.ForeignKey(User, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
text = models.CharField(max_length=1000)
likes = models.IntegerField(default=0)
parent_comment = models.ForeignKey('self', on_delete=models.CASCADE, null=True, related_name='child_comments')
Now I would like models for multiple topics (ShoppingList, Games,...). I came to two possible solutions and need help with deciding more suitable one.
1) Make Comment abstract and extend it for every new model wanted.
class ShoppingListComment(Comment):
shopping_list = models.ForeignKey(ShoppingList, related_name='shopping_comments', on_delete=models.CASCADE)
I could then query this game comments with something like:
ShoppingListComment.objects.all()
2) Add extra nullable Foreing keys directly to comment:
class BigCommentModel(models.Model):
who = models.ForeignKey(User, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
text = models.CharField(max_length=1000)
likes = models.IntegerField(default=0)
parent_comment = models.ForeignKey('self', on_delete=models.CASCADE, null=True, related_name='child_comments')
shopping_list = models.ForeignKey(ShoppingList, related_name='shopping_comments', on_delete=models.CASCADE, null=True),
game = models.ForeignKey(Game, related_name='game_comments', on_delete=models.CASCADE, null=True)
I could then query this game comments with something lile:
BigCommentModel.objects.filter(game__isnull=False)

Django REST framework many to many serializer

I got models:
class Car:
name = models.CharField(max_length=50, blank=True, default='')
class Wheel:
name = models.CharField(max_length=50, blank=True, default='')
cars = models.ManyToManyField(Car)
and serializers:
class CarSerializer(serializers.ModelSerializer):
class Meta:
model = Car
fields = ('name')
class WheelSerializer(serializers.ModelSerializer):
cars = CarSerializer(many=True, required=False)
class Meta:
model = Wheel
fields = ('name', 'cars')
It's works fine with Wheel case, it's shows me wheels and cars inside them. But I want to call cars and see wheels inside Cars. It's possible? Thanks!
Solution is to create new serializers:
class CarSerializer(serializers.ModelSerializer):
class Meta:
model = Car
fields = ('name')
class WheelSerializer(serializers.ModelSerializer):
class Meta:
model = Wheel
fields = ('name', 'cars')
class CarWheelSerializer(serializers.ModelSerializer):
cars = CarSerializer(many=True, required=False)
class Meta:
....
and WheelCarSerializer same way.

django-autocomplete-light not working - select2 is not a function

I'm using django-autocomplete-light with django 1.8.
It sometimes fails. Here is the javascript console error:
TypeError: $(...).select2 is not a function
;(function ($) {
$(document).on('autocompleteLightInitialize', '[data-autocomplete-light-function=select2]', function() {
var element = $(this);
// This widget has a clear button
$(this).find('option[value=""]').remove();
$(this).select2({
It worked fine yesterday and nothing has changed but today it is not working.
I'm also using django suit.
I feel that there is a javascript incompatibility between my django apps causing this random behavious but I do not know how to track down the cause.
Any ideas?
Here is all of my code:
# models.py
class Sample(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
class Doctor(models.Model):
name = models.CharField(max_length=200)
address = models.CharField(max_length=200, null=True, blank=True, default='')
def __unicode__(self):
return self.name
class Patient(models.Model):
name = models.CharField(max_length=200)
sample = models.OneToOneField(Sample, null=True, blank=True)
doctor = models.ForeignKey(Doctor, null=True, blank=True, default=None)
def __unicode__(self):
return self.name
----------
# urls.py
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^pat-sam-autocomplete/$', PatientSampleAutocomplete.as_view(), name='pat-sam-autocomplete',),
url(r'^pat-doc-autocomplete/$', PatientDoctorAutocomplete.as_view(), name='pat-doc-autocomplete',),
)
----------
# views.py
class PatientSampleAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated():
return Sample.objects.none()
qs = Sample.objects.all()
if self.q:
qs = qs.filter(name__icontains=self.q)
return qs
class PatientDoctorAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated():
return Doctor.objects.none()
qs = Doctor.objects.all()
if self.q:
qs = qs.filter(name__icontains=self.q)
return qs
--------------
# admin.py
from django import forms
from dal import autocomplete
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = ('__all__')
widgets = {
'sample': autocomplete.ModelSelect2(url='pat-sam-autocomplete'),
'doctor': autocomplete.ModelSelect2(url='pat-doc-autocomplete')
}
#admin.register(Doctor)
class DoctorAdmin(admin.ModelAdmin):
list_display = ('name', 'address')
#admin.register(Sample)
class SampleAdmin(admin.ModelAdmin):
list_display = ('name',)
#admin.register(Patient)
class PatientAdmin(admin.ModelAdmin):
list_display = ('name', 'sample')
form = PatientForm
I rearranged the INSTALLED_APPS in the settings.py and that seem to have fixed it:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'dal',
'dal_select2',
'suit',
'myapp',
'django.contrib.admin',
'django_extensions',
'simple_history',
'django_tables2',
'django.contrib.admindocs',
)

Issue with complex Django join query

I can't find a valid way with Django OMR in order to get : ( a raw query is also fine )
the Sites.sitename which made the Analysis where (Analysi_Items.name='somename' and Analysis_Items.value='somevalue') and (Analysi_items_name='somename' and Analysis_Items.value='somevalue') and (Analysis_items.name='somename' and Analysis_Items.value='somevalue').
class Sites(models.Model):
region = models.CharField(max_length=1000)
province = models.CharField(max_length=1000)
sitename = models.CharField(max_length=1000, primary_key=True)
class Meta:
verbose_name_plural = "Sites"
def __unicode__(self):
return self.sitename
class Analysis_Items(models.Model):
code = models.ForeignKey('Analysis')
name = models.CharField(max_lenght=100)
value = models.CharField(max_length=20)
class Meta:
verbose_name_plural = "Analysis Type"
class Analysis(models.Model):
date = models.DateField()
site = models.ForeignKey('Sites')
def __unicode__(self):
return str(self.date)
class Meta:
verbose_name_plural = "Analysis"
Hope this is clear enough. thank you in advance!
Site.objects.filter(analysis__analysis_items__name='some_name', analysis__analysis_items__value='some_value')
You can keep adding additional parameters in the same keep AND'ing them all together.