Django rest framework raw queries select not working - python

I want to use a raw query in order to make a JOIN in a many to many relationship, and show it in the Django Rest Framework.
But the "SELECT" part of the query is not working, and it shows whatever the serializer has in "fields" and thus the JOIN is also not working.
serializers.py:
class UserTestSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"
views.py:
class UserTestQuery(viewsets.ModelViewSet):
queryset = User.objects.raw('SELECT * ' +
'FROM users_user ' +
'INNER JOIN sysadmin_works_as ON users_user.user_id = sysadmin_works_as.employee_id;')
serializer_class = UserTestSerializer
I want to show a join in the API with these 3 models, so I must use raw SQL. Why is it not working?
And the models I'm using are:
class User(AbstractUser):
first_name = None
last_name = None
username = None
user_id = models.AutoField(primary_key=True)
email = models.EmailField(_('email address'), unique=True)
national_id_number = models.CharField(max_length=30)
f_name = models.CharField(max_length=100)
l_name = models.CharField(max_length=100)
star_count = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True,null=True)
is_superuser = models.BooleanField(default = False)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
updated_at = models.DateTimeField(auto_now=True,null=True)
deleted_at = models.DateTimeField(blank = True, null=True)
date_joined = models.DateTimeField(auto_now_add=True,null=True)
app_role = models.ForeignKey(App_roles,related_name='employee',on_delete=models.SET_NULL,blank=True,null=True) #Un Rol_de_Aplicacion le pertenece a muchos usuar
class Works_as(models.Model):
work_id = models.AutoField(primary_key=True)
started_at = models.DateTimeField(auto_now_add=True)
updates_at = models.DateTimeField(auto_now=True)
r_created_at = models.DateTimeField(auto_now_add=True)
r_updated_at = models.DateTimeField(auto_now=True)
r_deleted_at = models.DateTimeField(auto_now=False,blank=True,null=True)
employee = models.ForeignKey(User,related_name='works_as',on_delete=models.SET_NULL,blank=True,null=True)
position = models.ForeignKey(Position,related_name='works_as',on_delete=models.SET_NULL,blank=True,null=True)
class Position(models.Model):
position_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
description = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
deleted_at = models.DateTimeField(blank=True,null=True)
upper_position = models.ForeignKey('self',on_delete=models.SET_NULL,blank=True,null=True)
department = models.ForeignKey(Department,related_name='positions',on_delete=models.SET_NULL,blank=True,null=True)
hierarchy_level = models.OneToOneField(Employee_Hierarchy,related_name='position',on_delete=models.SET_NULL,blank=True,null=True)

Related

problem with django multitable inheritance and django-parler

i have these models:
class Product(TranslatableModel):
productId = models.UUIDField(default=uuid4, primary_key=True, editable=False)
translations = TranslatedFields(
title = models.CharField(max_length=100),
description = models.TextField(max_length = 2000)
)
picture = models.ImageField()
price = models.FloatField()
art_type = models.ForeignKey(ArtType, on_delete=models.SET_NULL, null = True,blank = True)
createdAt = models.DateTimeField(auto_now_add=True)
updatedAt = models.DateTimeField(auto_now=True)
purchase_num = models.PositiveBigIntegerField()
objects = InheritanceManager()
class Course(Product):
languages = models.ManyToManyField(Language)
isChaptersOpen = models.BooleanField(default=True)
but whenever i try to add a new course i get this error message in the django admin panel:
ImproperlyConfigured at /en/admin/products/product/
InheritanceQuerySet class does not inherit from TranslatableQuerySet
why this is happening

Django ORM multiple inner join in query

I want to be able to do queries involving multiple inner joins using Django ORM, here's my model (showing only relevant fields)
class Students(models.Model):
class Status(models.IntegerChoices):
preRegistered = 0 #No ha aceptado terminos y condiciones
Enabled = 1
Disabled = 2
Suspended = 3
Test = 4
id = models.AutoField(primary_key=True)
user = models.ForeignKey(Users, on_delete=models.CASCADE)
trainingPath = models.ForeignKey(trainingPaths, on_delete=models.CASCADE)
status = models.IntegerField(choices=Status.choices, default=0)
creationDate = models.DateTimeField(auto_now_add=True)
modificationDate = models.DateTimeField(auto_now=True)
class Meta():
db_table = 'Students'
class trainingPaths(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=70, blank=False, null=False)
shortName = models.CharField(max_length=10, blank=True)
creationDate = models.DateTimeField(auto_now_add=True)
modificationDate = models.DateTimeField(auto_now=True)
class Meta():
db_table = 'Training_Path'
class Courses(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=70, blank=False, null=False)
path = models.URLField(max_length=500, blank=True, null=True)
shortName = models.CharField(max_length=6, blank=True)
creationDate = models.DateTimeField(auto_now_add=True)
modificationDate = models.DateTimeField(auto_now=True)
course_image = models.URLField(max_length=200, blank=True)
class Meta():
db_table = 'Courses'
class CoursesXTrainingP(models.Model):
id = models.AutoField(primary_key=True)
trainingPath = models.ForeignKey(trainingPaths, on_delete=models.CASCADE)
course = models.ForeignKey(Courses, on_delete=models.CASCADE)
alternativeName = models.CharField(max_length=70, blank=True)
order = models.PositiveIntegerField(blank=False)
creationDate = models.DateTimeField(auto_now_add=True)
modificationDate = models.DateTimeField(auto_now=True)
class Meta():
db_table = 'Courses_X_Training_Paths'
I want to get the information of the courses that a student has according to the value of the "trainingPath".
this is my SQL query
select
courses.id, courses.`name`, courses.course_image
from
students
join
courses_x_training_paths
on
students.trainingPath_id = courses_x_training_paths.trainingPath_id
join
courses
on
courses_x_training_paths.course_id = courses.id
where
students.trainingPath_id=1;
I have tried several ways and none of them have worked, could you please help me?
You can filter with:
Courses.objects.filter(
coursesxtrainingp__trainingPath_id=1
)
The join on the Students model is not necessary, since we already know that the trainingPath_id is one by filtering on the CoursesXTrainingP model.
Note: normally a Django model is given a singular name, so Student instead of Students.
Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase, so it should be: modification_date instead of modificationDate.

While defining method for autosaving in CreateView for ManyToMany field Error shows

I have three Models, in third models Foreign Key and ManyToMany fields are linked, which are:
Personal_info Models.py
class Personal_info(models.Model):
gen_choices = (
("पुरुष", "पुरूष"),
("महिला", "महिला"),
("तेस्रो", "तेस्रो"),
)
pinfo_id = models.AutoField(primary_key=True)
userid = models.OneToOneField(User, on_delete=models.CASCADE)
nfullname = models.CharField(validators=[max_len_check], max_length=128)
efullname = models.CharField(validators=[max_len_check], max_length=128)
dob_ad = models.DateField()
dob_bs = models.DateField()
gender = models.CharField(max_length=6, choices=gen_choices)
citizen_no = models.CharField(max_length=56)
cissue_dist = models.ForeignKey(District, on_delete=models.CASCADE)
cissue_date = models.DateField()
language = models.CharField(max_length=56)
p_district = models.CharField(max_length=56)
p_vdc = models.CharField(max_length=56)
p_ward = models.CharField(max_length=2)
p_city = models.CharField(max_length=56)
t_district = models.CharField(max_length=56)
t_vdc = models.CharField(max_length=59)
t_ward = models.CharField(max_length=2)
t_city = models.CharField(max_length=56)
telephone = models.BigIntegerField(null=True, blank=True)
mobile = models.BigIntegerField()
mother_name = models.CharField(validators=[max_len_check], max_length=128)
mother_cit = models.CharField(max_length=10, null=True)
father_name = models.CharField(validators=[max_len_check], max_length=128)
father_cit = models.CharField(max_length=10, null=True)
gfather_name = models.CharField(validators=[max_len_check], max_length=128)
gfather_cit = models.CharField(max_length=10, null=True)
spose_name = models.CharField(validators=[max_len_check], max_length=128, null=True)
spose_cit = models.CharField(max_length=10, null=True, blank=True)
image = models.FileField(upload_to="photos/", null=True, blank=True)
cit_image = models.FileField(upload_to="citizens/")
inclu_image = models.FileField(upload_to="inclusions/", null=True)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
def __str__(self):
return str(self.efullname)
Educational Models.py
class Education(models.Model):
edu_id = models.AutoField(primary_key=True)
userid = models.ForeignKey(User, on_delete=models.CASCADE)
institute = models.CharField(max_length=255, validators=[max_len_check])
board = models.CharField(max_length=128, validators=[max_len_check1])
pexam = models.CharField(max_length=16, choices=exam_choices)
faculty = models.CharField(max_length=16, choices=fac_choices)
division = models.CharField(max_length=16, validators=[max_len_check2])
tmarks = models.IntegerField()
percent = models.FloatField(null=True, blank=True)
mainsub = models.CharField(max_length=16, validators=[max_len_check2])
image = models.FileField(upload_to="educations/", null=True, blank=True)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
def __str__(self):
return str(self.userid)
V_applied models.py
class V_applied(models.Model):
appNo = models.IntegerField(null=True, blank=True, default=add_one)
p_srlno = models.IntegerField(blank=True, null=0, default=0)
userid = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Vacancy,on_delete=models.CASCADE)
inclusive = models.ManyToManyField(Inclusive)
bank = models.CharField(max_length=128)
v_no = models.CharField(max_length=32, validators=[max_len_check1])
dep_date = models.DateField()
ser_fee = models.IntegerField()
image = models.FileField(upload_to="vouchers/")
personal_info = models.ForeignKey(Personal_info, on_delete=models.CASCADE, blank=True)
education = models.ManyToManyField(Education, blank=True, default=0)
active = models.BooleanField(default=True)
status = models.CharField(max_length=10, validators=[max_len_check], default="Pending")
remarks = models.CharField(max_length=56, validators=[max_len_check1], default="Pending")
comment = models.CharField(max_length=128, validators=[max_len_check2], blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
#property
def per_info(self):
return (self.personal_info.efullname, self.personal_info.gender, )
'''
def __str__(self):
return str(self.userid) + ':' + str(self.post)
Here I want to make auto save method in CreateView for ForeignKey & ManyToMany fields of V_applied models, for this I tried views.py as below:
#method_decorator(login_required(login_url='login'), name='dispatch')
class v_appliedadd(CreateView):
form_class = V_appliedForm
template_name = 'v_applied/v_applied_form.html'
success_url = '/v_applied/vapp_details/'
def form_valid(self, form):
form.instance.userid = self.request.user
form.instance.personal_info = Personal_info.objects.get(userid=self.request.user)
educationall = Education.objects.filter(userid=self.request.user)
for edu in educationall:
form.instance.education.add(edu)
return super().form_valid(form)
While saving data Error display like this:
ValueError at /v_applied/v_appliedadd/
"<V_applied: testuser>" needs to have a value for field "id" before this many-to-many relationship can be used.
Request Method: POST
Request URL: http://localhost:8000/v_applied/v_appliedadd/
Django Version: 3.0.8
Exception Type: ValueError
Exception Value:
"<V_applied: testuser>" needs to have a value for field "id" before this many-to-many relationship can be used.
Exception Location: C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related_descriptors.py in __init__, line 846
Python Executable: C:\Users\User\AppData\Local\Programs\Python\Python38\python.exe
Python Version: 3.8.1
Python Path:
['D:\\DjangoProject\\app_epf',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\lib',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38',
'C:\\Users\\User\\AppData\\Roaming\\Python\\Python38\\site-packages',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages']
Server time: Mon, 14 Sep 2020 23:09:21 +0545
I am new in python-django, please help me how to solve it.
form.instance.userid = self.request.user
form.instance.personal_info = Personal_info.objects.get(userid=self.request.user)
instance_from = form.save()
educationall = Education.objects.filter(userid=self.request.user)
for edu in educationall:
instance_edu = Education.objects.get(pk=edu.pk)
instance_from.education.add(instance_edu)
instance_from.save()
return super().form_valid(form)

How to get data from two models in Django

I have been trying to use with the a legacy database. I have created models file using inscpectdb but now I am not able to perform joins on the table.
I have two tables job_info and username_userid.
Here is my models.class file:
class UseridUsername(models.Model):
userid = models.IntegerField(blank=True, null=True)
username = models.CharField(max_length=100, blank=True, null=True)
class Meta:
managed = False
db_table = 'userid_username'
class LinuxJobTable(models.Model):
job_db_inx = models.AutoField(primary_key=True)
mod_time = models.IntegerField()
account = models.TextField(blank=True, null=True)
exit_code = models.IntegerField()
job_name = models.TextField()
id_job = models.IntegerField()
id_user = models.IntegerField()
class Meta:
managed = False
db_table = 'linux_job_table'
Heren is my serializable class :
class UseridUsernameSerializer(serializers.ModelSerializer):
class Meta:
model = UseridUsername
fields = ('userid','username')
class UserSerializer(serializers.ModelSerializer):
class Meta:
username = UseridUsernameSerializer(many=False)
model = LinuxJobTable
fields = ('account','mod_time','username')

Django foreign key(ManyToMany) field isn't added to DB table

class Organization(models.Model):
mLeader = models.ForeignKey(User)
mName = models.CharField(max_length=30, default='-')
mTel = models.CharField(max_length=15, default='-')
mAddress = models.TextField(default='-')
mType = models.CharField(max_length=1, default='A') # A : Daycare Center, B : private educational institute, C : Church, D : ...
owner = models.ForeignKey('auth.User', related_name='Organization')
def __str__(self) :
return self.mName
class OrganizationLeader(models.Model):
#private info
mUser = models.ForeignKey(User)
owner = models.ForeignKey('auth.User', related_name='Leader')
# mName = models.CharField(max_length=30, default='-')
class BusLine(models.Model):
mOrganization = models.ForeignKey(Organization)
mName = models.CharField(max_length=30, default='-')
mIsPrivate = models.BooleanField(default=True)
mCreated = models.DateTimeField(auto_now_add=True)
mIsCycle = models.BooleanField(default=False)
owner = models.ForeignKey('auth.User', related_name='lines')
class Meta:
ordering = ('mCreated', )
class BusStation(models.Model):
mName = models.CharField(max_length=30, default='-')
mCreated = models.DateTimeField(auto_now_add=True)
mOrder = models.IntegerField(default=None)
mIsStart = models.BooleanField(default=False)
mIsEnd = models.BooleanField(default=False)
mBusLine = models.ManyToManyField('BusLine', blank=True, null=True)
#변수명이 고정돼있어 접미사 붙이지 않음
mpoint = models.PointField(default=None)
objects = models.GeoManager()
Latitude = models.DecimalField(default=0.0, max_digits=10, decimal_places=6)
Longitude = models.DecimalField(default=0.0, max_digits=10, decimal_places=6)
owner = models.ForeignKey('auth.User', related_name='stations')
class Meta:
ordering = ['mOrder']
class Bus(models.Model):
mDriver = models.ForeignKey(User)
mDriving = models.BooleanField(default=False)
mCurrentStation = models.IntegerField(default=0)
mCreated = models.DateTimeField(auto_now_add=True)
mName = models.CharField(max_length=100)
mBusLine = models.ForeignKey('BusLine', on_delete=models.CASCADE, blank=True, null=True)
mArrive = models.BooleanField(default=False)
#LSB Data
#변수명이 고정돼있어 접미사 붙이지 않음
mpoint = models.PointField(default=None)
objects = models.GeoManager()
Latitude = models.DecimalField(default=0.0, max_digits=10, decimal_places=6)
Longitude = models.DecimalField(default=0.0, max_digits=10, decimal_places=6)
owner = models.ForeignKey('auth.User', related_name='buses')
def save(self, *args, **kwargs):
self.Latitude = self.mpoint.y
self.Longitude = self.mpoint.x
super(Bus, self).save(*args, **kwargs)
class Meta:
ordering = ('mCreated', )
class PassengerLogManager(models.Manager):
def create_log(self, id):
log = self.create(mBusId = id)
return log
class PassengerLog(models.Model):
mBusId = models.IntegerField()
mCreated = models.DateTimeField(auto_now_add=True,)
#JSON 필드에 버스의 한 회차 정류장당 탑승자 리스트가 저장됨
mLog = JSONField()
objects = PassengerLogManager()
class AppUser(models.Model):
#private info
mUser = models.ForeignKey(User)
mBaseDestination = models.ForeignKey(
BusStation,
verbose_name = 'BaseDestination',
default = '-',
)
mName = models.CharField(
verbose_name = 'UserName',
max_length=30,
blank = False,
default = '-'
)
mChild = models.ManyToManyField(
'self',
through = 'ParentToChildEntry',
verbose_name = 'Child',
through_fields = ('mParent','mChild'),
symmetrical = False,
)
owner = models.ForeignKey('auth.User', related_name='User')
def __str__(self) :
return self.mName
class ParentToChildEntry(models.Model) :
mName = models.CharField(
max_length = 20,
verbose_name = 'Title',
blank = False,
default = '-'
)
mParent = models.ForeignKey(
AppUser,
verbose_name = 'Parent',
related_name = 'Parent',
)
mChild = models.ManyToManyField(
AppUser,
verbose_name = 'Child',
related_name = 'Child',
)
def __str__(self) :
return self.mName
class OrganizationToUserEntry(models.Model) :
mName = models.CharField(
max_length = 20,
verbose_name = 'Title',
blank = False,
default ='-'
)
mOrganizations = models.ForeignKey(
Organization,
verbose_name = 'Organization'
)
mUsers = models.ManyToManyField(
AppUser,
verbose_name = 'Users'
)
def __str__(self) :
return self.mName
The code above is a Bus managing system model.(Django version 1.11.4)
Firstly when I tried to start and test this in admin,
the error (1054, "Unknown column 'DataMng_appuser.mBaseDestination_id' in 'field list'")
aroused so I flushed DB and migrated model.
However, When I tried to migrate this model, system returned me
[WARNINGS: DataMng.BusStation.mBusLine: (fields.W340) null has no effect on ManyToManyField.]
I repeatedly found how to solve this problem but I couldn't find.
Please tell me what I should do T_T. Thank you for reading.

Categories

Resources