'Users' object has no attribute 'values' django rest framework - python

I'm having a problem with serializing the data with joined tables. Am i doing this right? i'm just a newbie in django.
here's my models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
class Agency(models.Model):
agency_id = models.CharField(primary_key=True, max_length=50)
agency_shortname = models.CharField(max_length=20, blank=True, null=True)
agency_longname = models.CharField(max_length=255, blank=True, null=True)
date_created = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'agency'
class Users(AbstractBaseUser):
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
user_id = models.CharField(primary_key=True, max_length=50)
first_name = models.CharField(max_length=50, blank=True, null=True)
middle_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
username = models.CharField(unique=True, max_length=50, blank=True, null=True)
password = models.CharField(max_length=100, blank=True, null=True)
agency = models.OneToOneField(Agency, models.DO_NOTHING)
date_created = models.DateTimeField(blank=True, null=True)
active = models.CharField(max_length=8)
login_status = models.CharField(max_length=6)
last_login = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'users'
Then in my serializers.py
from rest_framework import serializers
from .models import Users, Agency
class UserDetailSerializer(serializers.ModelSerializer):
class Meta:
model = Users
fields = '__all__'
class AgencyDetailSerializer(serializers.ModelSerializer):
agency_id = UserDetailSerializer()
class Meta:
model = Agency
fields = ['agency_id','agency_shortname','agency_longname']
and my views.py
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from .serializers import UserDetailSerializer
from .models import Users, Agency
from rest_framework.permissions import IsAuthenticated
#api_view(['GET'])
#permission_classes([IsAuthenticated])
def userData(request):
username = request.GET.get('username')
r_type = request.GET.get('type')
user = Users.objects.get(username=username).values('user_id','first_name','middle_name','last_name','username','email','agency__agency_id','agency__agency_shortname','agency__agency_longname')
user_serializer = UserDetailSerializer(user, many=False)
return Response(user_serializer.data)
I'm getting an error of 'Users' object has no attribute 'values', what seems be the problem? i'm building api based application with vue.js and django rest framework. Thanks a lot

get queryset does not have values attribute, using filter instead.
user = Users.objects.filter(username=username).values(...)
Regarding your case, using get is enough and custom your Serializer like this:
class UserDetailSerializer(serializers.ModelSerializer):
class Meta:
model = Users
fields = '__all__'
agency = AgencyDetailSerializer(many=False, read_only=True)

Because values is not an attribute of model object. You can call values on queryset object. something like:
user = Users.objects.filter(username=username).values('user_id','first_name','middle_name','last_name','username','email','agency__agency_id','agency__agency_shortname','agency__agency_longname')
Note: You don't need to call values, just change this line to:
from rest_framework.generics import get_object_or_404
...
user = get_object_or_404(Users, **dict(username=username))
user_serializer = UserDetailSerializer(user)
...
Because serializer itself will handle it for you.

Related

Django REST Framework Serializer: Can't import model

I have a model i am trying to make a serializer out of however i cannot import the model into serializers.py. When i do i get this error:
ModuleNotFoundError: No module named 'airquality.air_quality'
This is the model i am trying to import
class Microcontrollers(models.Model):
name = models.CharField(max_length=25)
serial_number = models.CharField(max_length=20, blank=True, null=True)
type = models.CharField(max_length=15, blank=True, null=True)
software = models.CharField(max_length=20, blank=True, null=True)
version = models.CharField(max_length=5, blank=True, null=True)
date_installed = models.DateField(blank=True, null=True)
date_battery_last_replaced = models.DateField(blank=True, null=True)
source = models.CharField(max_length=10, blank=True, null=True)
friendly_name = models.CharField(max_length=45, blank=True, null=True)
private = models.BooleanField()
class Meta:
managed = True
db_table = 'microcontrollers'
verbose_name_plural = 'Microcontrollers'
def __str__(self):
return self.friendly_name
serializers.py
from rest_framework import serializers
from airquality.air_quality.models import Microcontrollers
class SourceStationsSerializer(serializers.ModelSerializer):
def create(self, validated_data):
pass
def update(self, instance, validated_data):
pass
class Meta:
model = Microcontrollers
fields = ['name']
The import is the one the IDE itself suggests i use when i type model = Microcontrollers in the serializer
use this if the model if the file in same directory
from .models import Microcontrollers
or if it is another directory wana import that model
from directoryname.models import Microcontrollers

Error Submitting a form in Django - django.db.utils.IntegrityError: NOT NULL constraint failed: account_deal.company_id

I'm working on a form that takes value from another model, and everything is loaded correctly, but when I submit the data the form is showing the following error:
django.db.utils.IntegrityError: NOT NULL constraint failed: account_deal.company_id
The consensus is that you have to add blank=True,null=True but that only prevents the error if the user doesn't type any data, in this case, I'm using an auto-generated date, so not sure why am I getting this error.
views.py
def close_lead(request):
if request.method == 'POST':
deal_form = DealForm(request.POST)
if deal_form.is_valid():
deal_form.save()
messages.success(request, 'You have successfully updated the status from open to Close')
id = request.GET.get('project_id', '')
obj = Leads.objects.get(project_id=id)
obj.status = "Closed"
obj.save(update_fields=['status'])
return HttpResponseRedirect(reverse('dashboard'))
else:
messages.error(request, 'Error updating your Form')
else:
id = request.GET.get('project_id', '')
obj = get_object_or_404(Leads, project_id=id)
m = obj.__dict__
keys = Leads.objects.get(project_id=m['project_id'])
form_dict = {'project_id':keys.project_id,
'agent':keys.agent,
'client':keys.point_of_contact,
'company':keys.company,
'service':keys.services
}
form = NewDealForm(request.POST or None,initial = form_dict)
return render(request,
"account/close_lead.html",
{'form':form})
models.py
from django.db import models
from django.conf import settings
from django_countries.fields import CountryField
from phone_field import PhoneField
from djmoney.models.fields import MoneyField
from ckeditor.fields import RichTextField
from django.utils import timezone
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
email = models.EmailField(blank=True,null=True, unique=True)
role = models.TextField(blank=True)
location = models.TextField(blank=True)
photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True)
def __str__(self):
return self.user.username
class Company(models.Model):
id = models.BigAutoField(primary_key=True)
company = models.CharField(blank=True, max_length=30, unique=True)
def __str__(self):
return self.company
class Client(models.Model):
id = models.BigAutoField(primary_key=True)
firstname = models.CharField(blank=True, max_length=30)
lastname = models.CharField(blank=True, max_length=15)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
position = models.CharField(blank=True, max_length=50)
country = CountryField(blank_label='(select country)')
email = models.EmailField(blank=True, max_length=100, default="this_is#n_example.com", unique=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
phone = PhoneField(default="(XX)-XXX-XXX")
def __str__(self):
return f'{self.firstname} {self.lastname}'
class Leads(models.Model):
CHOICES = (
('Illumination Studies','Illumination Studies'),
('Training','Training'),
('Survey Design','Survey Design'),
('Software License','Software License')
)
STATUS = (('Open','Open'),
('Closed','Closed'),
('Canceled', 'Canceled')
)
project_id = models.BigAutoField(primary_key=True)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
agent = models.ForeignKey(Profile, on_delete=models.CASCADE, default="agent")
created_at = models.DateTimeField(auto_now_add=True)
point_of_contact = models.ForeignKey(Client, on_delete=models.CASCADE)
expected_revenue = MoneyField(max_digits=14, decimal_places=2, default_currency='USD')
expected_licenses = models.IntegerField(blank=True)
country = CountryField(blank_label='(select country)')
status = models.CharField(max_length=10,choices=STATUS)
estimated_closing_date = models.DateField(blank=True)
services = models.CharField(max_length=20,choices=CHOICES)
def __str__(self):
return f'{self.project_id}'
class CallReport(models.Model):
CHOICES = (
('Phone Call','Phone Call'),
('Onsite Meeting', 'Onsite Meeting'),
('Client Offices', "Client Offices"),
('Other Location','Other Location'),
)
id = models.BigAutoField(primary_key=True)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
minutes_of_meeting = RichTextField(blank=True, null=True)
client_POC = models.CharField(max_length=100)
location = models.CharField(max_length=50,choices=CHOICES, default='Phone Call')
title = models.CharField(max_length=100)
date = models.DateField()
ACTeQ_representative = models.ForeignKey(Profile, on_delete=models.CASCADE, default='agent')
def __str__(self):
return f'Call Report for {self.company}, on the {self.date}'
class Deal(models.Model):
CHOICES = (
('Illumination Studies','Illumination Studies'),
('Training','Training'),
('Survey Design','Survey Design'),
('Software License','Software License')
)
project_id = models.ForeignKey(Leads, on_delete=models.CASCADE, default="project_id")
agent = models.ForeignKey(Profile, on_delete=models.CASCADE, default="agent")
service = models.CharField(max_length=20,choices=CHOICES)
closing_date = models.DateField(auto_now_add=True)
client = models.ForeignKey(Client, on_delete=models.CASCADE,default='client')
licenses = models.IntegerField(blank=True)
revenue = MoneyField(max_digits=14, decimal_places=2, default_currency='USD')
comments = models.TextField(blank=True,null=True)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
Lastly, the form:
from .models import Profile, Client, Company, Leads, CallReport, Deal
from django import forms
from django.contrib.auth.models import User
from django.contrib.admin.widgets import AdminDateWidget
from django.forms.fields import DateField
class DateInput(forms.DateInput):
input_type = 'date'
class UserEditForm(forms.ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email')
class ProfileEditForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('role', 'photo', 'location')
class ClientForm(forms.ModelForm):
class Meta:
model = Client
fields = ('firstname', 'lastname',"position",'company','country','email','phone')
class CompanyForm(forms.ModelForm):
class Meta:
model = Company
fields = ('company',)
class LeadsForm(forms.ModelForm):
class Meta:
model = Leads
fields = ('project_id','company','agent','point_of_contact','services','expected_licenses',
'expected_revenue','country', 'status', 'estimated_closing_date'
)
widgets = {'estimated_closing_date': DateInput()}
class CallForm(forms.ModelForm):
class Meta:
model = CallReport
fields = ('company','title','location', 'ACTeQ_representative','client_POC','minutes_of_meeting','date')
widgets = {'date':DateInput()}
class DealForm(forms.ModelForm):
class Meta:
model = Deal
fields = ['agent','project_id','service','client', 'licenses','revenue', 'comments']
class EditLeadsForm(forms.ModelForm):
class Meta:
model = Leads
fields = ('project_id','company','agent','point_of_contact','expected_revenue',
'expected_licenses','country', 'status', 'estimated_closing_date',
'services')
widgets = {'date': DateInput()}
class NewDealForm(forms.ModelForm):
class Meta:
model = Deal
fields = ['project_id','agent','client','company','service', 'licenses','revenue', 'comments']
I have already deleted the database and run the migrations, and the error persists.

Django Rest Framework (DRF) how to get value of GenericRelation field?

at my models.py I have a "Movies" model with the following field setup:
video_stream_relation = GenericRelation(VideoStreamInfo, related_query_name='video_stream_relation')
This GenericRelation field points to the following model class:
class VideoStreamInfo(models.Model):
objects = RandomManager()
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
content_type = models.ForeignKey(ContentType, limit_choices_to=referential_stream_models, on_delete=models.CASCADE, verbose_name=_("Content Type"))
object_id = models.CharField(max_length=36, verbose_name=_("Object ID"))
content_object = GenericForeignKey('content_type', 'object_id')
index = models.IntegerField(verbose_name=_("Stream Index"), blank=False)
bit_rate = models.IntegerField(verbose_name=_("Bitrate (bps)"), blank=True, null=True, editable=False)
codec_name = models.CharField(verbose_name=_("Codec Name"), blank=True, null=True, editable=False, max_length=255)
width = models.IntegerField(verbose_name=_("Width"), blank=True, null=True, editable=False)
height = models.IntegerField(verbose_name=_("Height"), blank=True, null=True, editable=False)
date_added = models.DateTimeField(auto_now_add=True, verbose_name=_("Date Added"))
Now the Question is how can I get video_stream_relation.codec_name value in a ModelSerializer like this:
class MovieSerializer(serializers.ModelSerializer):
id = serializers.PrimaryKeyRelatedField(queryset=Movies.objects.all())
class Meta:
model = Movies
fields = ('id',
...)
I want to be able to display the codec_name as a API JsonResponse.
If needed, this is how my API view currently looks like:
#api_view(['GET',])
#authentication_classes([JSONWebTokenAuthentication])
#permission_classes([AllowAny])
def movies(request):
if request.method == 'GET':
obj = Movies.objects.all()
serializer = MovieSerializer(obj, many=True)
return JsonResponse(serializer.data, safe=False)
If I try to add the video_stream_relation field to my MovieSerializer I get back the following error:
TypeError: Object of type GenericRelatedObjectManager is not JSON
serializable
Thanks in advance.
You can create a model serializer for VideoStreamInfo and use it in MovieSerializer as a related manager like this:
from rest_framework import serializers
class VideoStreamInfoSerializer(serializers.ModelSerializer):
class Meta:
model = VideoStreamInfo
fields = ('codec_name', )
class MovieSerializer(serializers.ModelSerializer):
video_stream_relation = VideoStreamInfoSerializer(many=True, read_only=True)
id = serializers.PrimaryKeyRelatedField(queryset=Movies.objects.all())
class Meta:
model = Movies
fields = ('id',
'video_stream_relation',
...
)

How to save three related models in one DRF endpoint?

I have 4 related models and I need to implement the functionality to consistently create instances of these models in a database in one post query. For this I use override of the APIView class post method.
models
class VendorContacts(models.Model):
contact_id = models.AutoField(primary_key=True)
vendor = models.OneToOneField('Vendors', on_delete=models.CASCADE)
contact_name = models.CharField(max_length=45, blank=True)
phone = models.CharField(max_length=45, blank=True)
email = models.CharField(max_length=80, blank=True, unique=True)
class Meta:
db_table = 'vendor_contacts'
class VendorModuleNames(models.Model):
vendor = models.OneToOneField('Vendors', on_delete=models.CASCADE, primary_key=True)
module = models.ForeignKey(Modules, models.DO_NOTHING)
timestamp = models.DateTimeField(auto_now=True)
class Meta:
db_table = 'vendor_module_names'
unique_together = (('vendor', 'module'),)
class Vendors(models.Model):
COUNTRY_CHOICES = tuple(COUNTRIES)
vendorid = models.AutoField(primary_key=True)
vendor_name = models.CharField(max_length=45, unique=True)
country = models.CharField(max_length=45, choices=COUNTRY_CHOICES)
nda = models.DateField(blank=True, null=True)
user_id = models.ForeignKey('c_users.CustomUser', on_delete=models.PROTECT)
timestamp = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = 'vendors'
unique_together = (('vendorid', 'timestamp'),)
class Modules(models.Model):
MODULES_NAME =tuple(MODULES)
mid = models.AutoField(primary_key=True)
module_name = models.CharField(max_length=50, choices=MODULES_NAME)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now=True)
class Meta:
db_table = 'modules'
unique_together = (('mid', 'timestamp'),)
serializer.py
class VendorsSerializer(serializers.ModelSerializer):
class Meta:
model = Vendors
fields = ('vendor_name',
'country',
'nda',)
class VendorContactSerializer(serializers.ModelSerializer):
class Meta:
model = VendorContacts
fields = (
'contact_name',
'phone',
'email',)
class VendorModulSerializer(serializers.ModelSerializer):
class Meta:
model = VendorModuleNames
fields = ('module',)
class ModulesSerializer(serializers.ModelSerializer):
class Meta:
model = Modules
fields = ('module_name', )
views.py
class VendorsCreateView(APIView):
"""Create new vendor instances from form"""
def post(self, request, *args, **kwargs):
vendor_serializer = VendorsSerializer(data=request.data)
vendor_contact_serializer = VendorContactSerializer(data=request.data)
vendor_modules_serializer = VendorModulSerializer(data=request.data)
module_serializer = ModulesSerializer(data=request.data)
try:
vendor_serializer.is_valid(raise_exception=True) \
and vendor_contact_serializer.is_valid(raise_exception=True) \
and vendor_modules_serializer.is_valid(raise_exception=True) \
and module_serializer.is_valid(raise_exception=True)
vendor_serializer.save(user_id=request.user)
# ....
# Some new logic here ????
# ...
except ValidationError:
return Response({"errors": (vendor_serializer.errors,
vendor_contact_serializer.errors,
vendor_modules_serializer.errors
)},
status=status.HTTP_400_BAD_REQUEST)
else:
return Response(request.data, status=status.HTTP_200_OK)
There is no problem saving one Vendor model, but I can't imagine how to save cascading all related models in a single request.
save returns the newly saved object, which you can then pass into the subsequent save() methods:
vendor = vendor_serializer.save(user_id=request.user)
module = module_serializer.save()
vendor_module = vendor_modules_serializer.save(module=module, vendor=vendor)
vendor_contact = vendor_contact_serializer.save(vendor=vendor)

In Django restframework, foreign key value is not getting in HyperlinkedModelserializer

Models.py
from django.db import models
class BusinessType(models.Model):
method = models.CharField(max_length=25)
class Vendor(models.Model):
first_name = models.CharField(max_length=25)
middle_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=25)
nick_name = models.CharField(max_length=10)
email = models.CharField(max_length=30)
company = models.CharField(max_length=25)
phone = models.CharField(max_length=15)
mobile = models.CharField(max_length=10)
fax = models.CharField(max_length=10)
billing_address_street = models.CharField(max_length=120)
billing_address_city = models.CharField(max_length=20)
billing_address_state = models.CharField(max_length=20)
billing_address_zip = models.CharField(max_length=6)
billing_address_country = models.CharField(max_length=20)
shipping_address_street = models.CharField(max_length=120)
shipping_address_city = models.CharField(max_length=20)
shipping_address_state = models.CharField(max_length=20)
shipping_address_zip = models.CharField(max_length=6)
shipping_address_country = models.CharField(max_length=20)
notes = models.CharField(max_length=120)
gstin = models.CharField(max_length=25, null=True)
tin = models.CharField(max_length=25, null=True)
business_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE)
Serializers.py
from rest_framework import serializers
from .models import Vendor,BusinessType
class BusinessTypeSerializer(serializers.HyperlinkedModelSerializer):
[enter image description here][1]
class Meta:
model = BusinessType
fields = ('id','method')
class VendorSerializer(serializers.HyperlinkedModelSerializer):
business_type = serializers.CharField(source='business_type.method')
class Meta:
model = Vendor
fields = ('id','first_name','middle_name','last_name','nick_name','email','company','phone','mobile','fax','billing_address_street','billing_address_city','billing_address_state','billing_address_zip','billing_address_country','shipping_address_street','shipping_address_city','shipping_address_state','shipping_address_zip','shipping_address_country','notes','gstin','tin','business_type')
In Django restframework, foreign key value is not getting in HyperlinkedModelserializer in 'business_type' field. When I tried to post method after declaring foreign key field, it says:
"AssertionError: The .create() method does not support nested
writable fields by default. Write an explicit .create() method for
serializer UserSerializer, or set read_only=True"

Categories

Resources