For loop issue writing multiple lines to database - python
The for loop below has an issue when writing to the database. Only the first record is coming through, i believe it's because report_name_sc = reportlist is writing the query set to the database. How can I get it to write a single line for each report_id?
checkedlist = request.GET.getlist('report_id')
reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True)
for i in checkedlist:
requestsave = QVFormAccessRequest(ntname_id = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title
,report_id = i, report_name_sc = reportlist, accesslevel_id = '7', phi = '1', access_beg_date = '2017-01-01', access_end_date = '2017-01-31')
requestsave.save()
Models.py added as requested, checked list is a collection of check boxes getting report_id:
from __future__ import unicode_literals
from django.utils import timezone
from django.contrib.auth.models import (AbstractBaseUser,PermissionsMixin)
from django.db import models
from django.conf import settings
from django.forms import ModelForm
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
username = models.CharField(max_length=7, unique=True)
formattedusername = models.CharField(max_length=11, unique=True, primary_key = True)
first_name = models.CharField(max_length=40)
last_name = models.CharField(max_length=140)
date_joined = models.DateTimeField(default=timezone.now)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_cfo = models.BooleanField(default=False)
facility = models.CharField(max_length=140)
officename = models.CharField(max_length=100)
jobdescription = models.CharField(max_length=140)
positioncode = models.CharField(max_length = 100)
positiondescription = models.CharField(max_length=140)
coid = models.CharField(max_length=5)
streetaddress = models.CharField(max_length=140)
title = models.CharField(max_length=100)
USERNAME_FIELD = 'username'
class Meta:
app_label = 'accounts'
db_table = "user"
def save(self, *args, **kwargs):
self.formattedusername = '{domain}\{username}'.format(
domain='HCA', username=self.username)
super(User, self).save(*args, **kwargs);
def get_short_name(self):
return self.username
# REQUIRED_FIELDS = "username"
def __str__(self):
return '%s - %s %s' % (self.username, self.first_name, self.last_name)
class FacilityDimension(models.Model):
unit_num = models.CharField(db_column='Unit_Num', max_length=5, blank=True, null=True) # Field name made lowercase.
company_code = models.CharField(db_column='Company_Code', max_length=1, blank=True, null=True) # Field name made lowercase.
coid = models.CharField(db_column='Coid',primary_key=True, serialize=False, max_length=5) # Field name made lowercase.
coid_name = models.CharField(db_column='COID_Name', max_length=50, blank=True, null=True) # Field name made lowercase.
c_level = models.CharField(db_column='C_Level', max_length=6, blank=True, null=True) # Field name made lowercase.
company_name = models.CharField(db_column='Company_Name', max_length=50, blank=True, null=True) # Field name made lowercase.
s_level = models.CharField(db_column='S_Level', max_length=6, blank=True, null=True) # Field name made lowercase.
sector_name = models.CharField(db_column='Sector_Name', max_length=50, blank=True, null=True) # Field name made lowercase.
b_level = models.CharField(db_column='B_Level', max_length=6, blank=True, null=True) # Field name made lowercase.
group_name = models.CharField(db_column='Group_Name', max_length=50, blank=True, null=True) # Field name made lowercase.
r_level = models.CharField(db_column='R_Level', max_length=6, blank=True, null=True) # Field name made lowercase.
division_name = models.CharField(db_column='Division_Name', max_length=50, blank=True, null=True) # Field name made lowercase.
d_level = models.CharField(db_column='D_Level', max_length=6, blank=True, null=True) # Field name made lowercase.
market_name = models.CharField(db_column='Market_Name', max_length=50, blank=True, null=True) # Field name made lowercase.
f_level = models.CharField(db_column='F_Level', max_length=6, blank=True, null=True) # Field name made lowercase.
cons_facility_name = models.CharField(db_column='Cons_Facility_Name', max_length=50, blank=True, null=True) # Field name made lowercase.
lob_code = models.CharField(db_column='LOB_Code', max_length=3, blank=True, null=True) # Field name made lowercase.
lob_name = models.CharField(db_column='LOB_Name', max_length=20, blank=True, null=True) # Field name made lowercase.
sub_lob_code = models.CharField(db_column='Sub_LOB_Code', max_length=3, blank=True, null=True) # Field name made lowercase.
sub_lob_name = models.CharField(db_column='Sub_LOB_Name', max_length=20, blank=True, null=True) # Field name made lowercase.
state_code = models.CharField(db_column='State_Code', max_length=2, blank=True, null=True) # Field name made lowercase.
pas_id_current = models.CharField(db_column='PAS_ID_Current', max_length=8, blank=True, null=True) # Field name made lowercase.
pas_current_name = models.CharField(db_column='PAS_Current_Name', max_length=40, blank=True, null=True) # Field name made lowercase.
pas_id_future = models.CharField(db_column='PAS_ID_Future', max_length=8, blank=True, null=True) # Field name made lowercase.
pas_future_name = models.CharField(db_column='PAS_Future_Name', max_length=40, blank=True, null=True) # Field name made lowercase.
summary_7_member_ind = models.CharField(db_column='Summary_7_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
summary_8_member_ind = models.CharField(db_column='Summary_8_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
summary_phys_svc_member_ind = models.CharField(db_column='Summary_Phys_Svc_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
summary_asd_member_ind = models.CharField(db_column='Summary_ASD_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
summary_imaging_member_ind = models.CharField(db_column='Summary_Imaging_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
summary_oncology_member_ind = models.CharField(db_column='Summary_Oncology_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
summary_cath_lab_member_ind = models.CharField(db_column='Summary_Cath_Lab_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
summary_intl_member_ind = models.CharField(db_column='Summary_Intl_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
summary_other_member_ind = models.CharField(db_column='Summary_Other_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
pas_coid = models.CharField(db_column='PAS_COID', max_length=5, blank=True, null=True) # Field name made lowercase.
pas_status = models.CharField(db_column='PAS_Status', max_length=1, blank=True, null=True) # Field name made lowercase.
company_code_operations = models.CharField(db_column='Company_Code_Operations', max_length=3, blank=True, null=True) # Field name made lowercase.
osg_pas_ind = models.CharField(db_column='OSG_PAS_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
abs_facility_member_ind = models.CharField(db_column='ABS_Facility_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
abl_facility_member_ind = models.CharField(db_column='ABL_Facility_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
intl_pmis_member_ind = models.CharField(db_column='INTL_PMIS_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
hsc_member_ind = models.CharField(db_column='HSC_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
loaddate = models.DateTimeField(db_column='LoadDate', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'Facility_Dimension'
class QvDatareducecfo(models.Model):
cfo_fname = models.CharField(db_column='CFO_FName', max_length=100, blank=True, null=True) # Field name made lowercase.
cfo_lname = models.CharField(db_column='CFO_LName', max_length=100, blank=True, null=True) # Field name made lowercase.
cfo_ntname = models.OneToOneField(settings.AUTH_USER_MODEL,db_column='CFO_NTName',max_length=11, primary_key=True) # Field name made lowercase.
cfo_type = models.IntegerField(db_column='CFO_Type', blank=True, null=True) # Field name made lowercase.
org_level_id = models.IntegerField(db_column='Org_Level_ID', blank=True, null=True) # Field name made lowercase.
org_level = models.CharField(db_column='Org_Level', max_length=255, blank=True, null=True) # Field name made lowercase.
unit_no = models.CharField(db_column='Unit_No', max_length=10, blank=True, null=True) # Field name made lowercase.
dr_code = models.CharField(db_column='DR_Code', max_length=255, blank=True, null=True) # Field name made lowercase.
dr_name = models.CharField(db_column='DR_Name', max_length=255, blank=True, null=True) # Field name made lowercase.
cfo_dr_code = models.CharField(db_column='CFO_DR_Code', max_length=255, blank=True, null=True) # Field name made lowercase.
cfo_dr_name = models.CharField(db_column='CFO_DR_Name', max_length=255, blank=True, null=True) # Field name made lowercase.
b_level = models.CharField(db_column='B_Level', max_length=6, blank=True, null=True) # Field name made lowercase.
group_name = models.CharField(db_column='Group_Name', max_length=255, blank=True, null=True) # Field name made lowercase.
load_date = models.DateTimeField(db_column='Load_Date', blank=True, null=True) # Field name made lowercase.
beg_date = models.DateTimeField(db_column='Beg_Date', blank=True, null=True) # Field name made lowercase.
end_date = models.DateTimeField(db_column='End_Date', blank=True, null=True) # Field name made lowercase.
active = models.IntegerField(db_column='Active', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'QV_DataReduceCFO'
def __str__(self):
return str(self.cfo_ntname)
class QvReportList(models.Model):
qv_dept_id = models.CharField(db_column='QV_Dept_ID', max_length=100) # Field name made lowercase.
report_id = models.CharField(db_column='Report_ID',primary_key=True, max_length=100, serialize=False) # Field name made lowercase.
report_name = models.CharField(db_column='Report_Name', max_length=255, blank=True, null=True) # Field name made lowercase.
report_name_sc = models.CharField(db_column='Report_Name_SC', max_length=255, blank=True, null=True) # Field name made lowercase.
qv_filename = models.CharField(db_column='QV_FileName', max_length=255, blank=True, null=True) # Field name made lowercase.
report_access = models.CharField(db_column='Report_Access', max_length=20, blank=True, null=True) # Field name made lowercase.
report_group_id = models.IntegerField(db_column='Report_Group_ID', blank=True, null=True) # Field name made lowercase.
report_sub_group_id = models.IntegerField(db_column='Report_Sub_Group_ID', blank=True, null=True) # Field name made lowercase.
load_date = models.DateTimeField(db_column='Load_Date', blank=True, null=True) # Field name made lowercase.
approver_fname = models.CharField(db_column='Approver_FName', max_length=255, blank=True, null=True) # Field name made lowercase.
approver_lname = models.CharField(db_column='Approver_LName', max_length=255, blank=True, null=True) # Field name made lowercase.
approver_ntname = models.CharField(db_column='Approver_NTName', max_length=255, blank=True, null=True) # Field name made lowercase.
beg_date = models.DateTimeField(db_column='Beg_Date', blank=True, null=True) # Field name made lowercase.
end_date = models.DateTimeField(db_column='End_Date', blank=True, null=True) # Field name made lowercase.
active = models.IntegerField(db_column='Active', blank=True, null=True) # Field name made lowercase.
approval_id = models.IntegerField(db_column='Approval_ID', blank=True, null=True) # Field name made lowercase.
role_based_id = models.IntegerField(db_column='Role_Based_ID', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'QV_Report_List'
class QVReportAccess(models.Model):
user_status = models.CharField(db_column='User_Status', max_length = 20) # Field name made lowercase.
ntname = models.OneToOneField(settings.AUTH_USER_MODEL,db_column='NTName', max_length=11,primary_key=True, serialize=False) # Field name made lowercase.
report_name = models.CharField(db_column='Report_Name', max_length=50, blank=True, null=True) # Field name made lowercase.
report_name_sc = models.CharField(db_column='Report_Name_SC', max_length=30, blank=True, null=True) # Field name made lowercase.
datareduce_report_code = models.IntegerField(db_column='DataReduce_Report_Code', blank=True, null=True) # Field name made lowercase.
role_based_id = models.IntegerField(db_column='Role_Based_ID', blank=True, null=True) # Field name made lowercase.
report_id = models.OneToOneField(QvReportList,db_column='Report_ID', max_length=100, blank=True, null=True) # Field name made lowercase.
report_group_id = models.IntegerField(db_column='Report_Group_ID', blank=True, null=True) # Field name made lowercase.
report_access = models.CharField(db_column='Report_Access', max_length=50, blank=True, null=True) # Field name made lowercase.
sr_datareduce_summary_code = models.CharField(db_column='SR_DataReduce_Summary_Code', max_length=10, blank=True, null=True) # Field name made lowercase.
sr_datareduce_patient_code = models.CharField(db_column='SR_DataReduce_Patient_Code', max_length=10, blank=True, null=True) # Field name made lowercase.
userid = models.IntegerField(db_column='UserID', blank=True, null=True) # Field name made lowercase.
user_group_id = models.IntegerField(db_column='User_Group_ID', blank=True, null=True)
access_level_id = models.IntegerField(db_column='Access_Level_ID', blank=True, null=True)
active = models.IntegerField(db_column='Active', blank=True, null=True)
qv_statusid = models.IntegerField(db_column='QV_StatusID', blank=True, null=True)
employee_status_id = models.IntegerField(db_column='Employee_Status_ID', blank = True, null = True)
new_user = models.IntegerField(db_column='New_User', blank = True, null = True)
new_access = models.IntegerField(db_column='New_Access', blank = True, null = True)
new_report = models.IntegerField(db_column='New_Report', blank = True, null = True)
changed_row = models.IntegerField(db_column='Changed_Row',blank = True, null = True)
last_change_date = models.DateTimeField(db_column='Last_Change_Date', blank=True, null=True) # Field name made lowercase.
access_beg_date = models.DateTimeField(db_column='Access_Beg_Date', blank=True, null=True) # Field name made lowercase.
access_end_date = models.DateTimeField(db_column='Access_End_Date', blank=True, null=True) # Field name made lowercase.
report_beg_date = models.DateTimeField(db_column='Report_Beg_Date', blank=True, null=True) # Field name made lowercase.
report_end_date = models.DateTimeField(db_column='Report_End_Date', blank=True, null=True) # Field name made lowercase.
qv_startdate = models.DateTimeField(db_column='QV_StartDate', blank=True, null=True) # Field name made lowercase.
load_date = models.DateTimeField(db_column='Load_Date', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'QV_ReportAccess'
class QVFormAccessRequest(models.Model):
ntname = models.CharField(max_length=11)
first_name = models.CharField(max_length=40)
last_name = models.CharField(max_length=140)
coid = models.CharField(max_length=5)
facility = models.CharField(max_length=140)
title = models.CharField(max_length=100)
report_id = models.CharField(max_length=100)
report_name_sc = models.CharField(max_length=100, blank=True, null=True)
accesslevel_id = models.CharField(max_length=100)
phi = models.BooleanField(default=False)
access_beg_date = models.DateTimeField(blank=True, null=True) # Field name made lowercase.
access_end_date = models.DateTimeField(blank=True, null=True) # Field name made lowercase.
class Meta:
managed = True
db_table = 'QV_FormAccessRequest'
class DjangoMigrations(models.Model):
app = models.CharField(max_length=255)
name = models.CharField(max_length=255)
applied = models.DateTimeField()
class Meta:
managed = False
db_table = 'django_migrations'
class Sysdiagrams(models.Model):
name = models.CharField(max_length=128)
principal_id = models.IntegerField()
diagram_id = models.AutoField(primary_key=True)
version = models.IntegerField(blank=True, null=True)
definition = models.BinaryField(blank=True, null=True)
class Meta:
managed = False
db_table = 'sysdiagrams'
unique_together = (('principal_id', 'name'),)
Your QVFormAccessRequest model specifies ntname to be a primary key. So, there cannot be to model instances with the same primary key.
In your loop, you are iterating over checkedlist, but you always set the same ntname_id, so you are overwriting the previous object.
I suspect that you need to change your model to support what you want to achieve. Maybe, it is enough to remove the primary key constraint from ntname and let Django create a surrogate key (artificial key) for you.
Related
RecursionError : maximum recursion depth exceeded while calling a Python object
I am getting an error in admin console while trying to open a model . How to fix it Model.py class TbSysEmailconfig(models.Model): id = models.ForeignKey('self', models.DO_NOTHING, db_column='Id', primary_key=True) # Field name made lowercase. emailtemplateid = models.ForeignKey(TbMasEmailtemplate, models.DO_NOTHING, db_column='EmailTemplateId') emailfromname = models.CharField(db_column='EmailFromName', max_length=100, blank=True, null=True) emailfrom = models.CharField(db_column='EmailFrom', max_length=100) credential = models.CharField(db_column='Credential', max_length=100) password = models.CharField(db_column='Password', max_length=100) post = models.IntegerField(db_column='Post', blank=True, null=True) host = models.CharField(db_column='Host', max_length=100) priority = models.CharField(db_column='Priority', max_length=100, blank=True, null=True) maximumday = models.IntegerField(db_column='MaximumDay', blank=True, null=True) maximumminute = models.IntegerField(db_column='MaximumMinute', blank=True, null=True) systemid = models.IntegerField(db_column='SystemId') partfiletemplate = models.CharField(db_column='PartFileTemplate', max_length=500, blank=True, null=True) comment = models.CharField(db_column='Comment', max_length=1000, blank=True, null=True) ismaildefault = models.SmallIntegerField(db_column='IsMailDefault') maildefault = models.CharField(db_column='MailDefault', max_length=4000, blank=True, null=True) createddate = models.DateTimeField(db_column='CreatedDate') createdbyuserid = models.IntegerField(db_column='CreatedByUserId') updateddate = models.DateTimeField(db_column='UpdatedDate') updatedbyuserid = models.IntegerField(db_column='UpdatedByUserId') delflag = models.SmallIntegerField(db_column='DelFlag') class Meta: db_table = 'TB_SYS_EmailConfig' admin.py from django.contrib import admin from .model import TbSysEmailconfig #Modifire admin.site.register(TbSysEmailconfig) When I select some item it show this error
Remove the id field from your model, as you have referenced it as a foreign key to the model itself. The id field is automatically generated if no field in the model is explicitly chosen.
how can I get data from a table that is liked to a table that is liked to another one it self?
I have three tables,result, course and study, they are like follows class Study(models.Model): id_study = models.IntegerField(primary_key=True) study_name = models.CharField(max_length=45) description = models.CharField(max_length=45, blank=True, null=True) language = models.CharField(max_length=45) number_of_years = models.CharField(max_length=45) class Course(models.Model): id_course = models.AutoField(primary_key=True) course_name = models.CharField(max_length=45, blank=True, null=True) description = models.CharField(max_length=45, blank=True, null=True) credits = models.CharField(max_length=45, blank=True, null=True) teacher_id_teacher = models.ForeignKey('Teacher', models.DO_NOTHING, db_column='teacher_id_teacher') study_id_study = models.ForeignKey('Study', models.DO_NOTHING, db_column='study_id_study') class Exam(models.Model): id_exam = models.AutoField(primary_key=True) room = models.CharField(max_length=45, blank=True, null=True) resit = models.CharField(max_length=45, blank=True, null=True) date = models.DateField(blank=True, null=True) time = models.TimeField(blank=True, null=True) course_id_course = models.ForeignKey(Course, models.DO_NOTHING, db_column='course_id_course') class Result(models.Model): id_result = models.AutoField(primary_key=True) grade = models.IntegerField(blank=True, null=True) exam_id_exam = models.ForeignKey(Exam, models.DO_NOTHING, db_column='exam_id_exam') date = models.DateField(blank=True, null=True) student_id_student = models.ForeignKey('Student', models.DO_NOTHING, db_column='student_id_student') passed = models.CharField(max_length=45, blank=True, null=True) I want to get a result object depending on the study_id I give Result depends on Exam, Exam depends on Course and Course depends on study Thanks in advance
You can follow relationships in queries by using the double underscore notation Result.objects.filter( exam_id_exam__course_id_course__study_id_study__id=study_id ) For what it's worth: you have an odd naming convention for your foreign keys, usually a foreign key to a model named Exam would be named exam, you are already setting db_column for each foreign key so you don't need to name them this way. If you changed their names to be the model name lowercase it would look like this which is probably more readable Result.objects.filter(exam__course__study__id=study_id)
How can I access objects in a django model composed of two foreign keys?
These are the relevant classes of my app. I want basically understand if the a certain user (form AuthUser) is linked to a business (from BusinessInformation) by looking at UserBusinessInformation. Thanks class AuthUser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.IntegerField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.CharField(max_length=254) is_staff = models.IntegerField() is_active = models.IntegerField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'auth_user' class BusinessInformation(models.Model): business_id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) lat = models.CharField(max_length=255) lng = models.CharField(max_length=255) formatted_address = models.CharField(max_length=255, blank=True, null=True) locality = models.CharField(max_length=255, blank=True, null=True) country = models.CharField(max_length=255, blank=True, null=True) administrative_area_level_5 = models.CharField(max_length=255, blank=True, null=True) administrative_area_level_4 = models.CharField(max_length=255, blank=True, null=True) administrative_area_level_3 = models.CharField(max_length=255, blank=True, null=True) administrative_area_level_2 = models.CharField(max_length=255, blank=True, null=True) administrative_area_level_1 = models.CharField(max_length=255, blank=True, null=True) postal_code = models.CharField(max_length=45, blank=True, null=True) route = models.CharField(max_length=255, blank=True, null=True) street_number = models.CharField(max_length=45, blank=True, null=True) phone = models.CharField(max_length=255, blank=True, null=True) phone2 = models.CharField(max_length=255, blank=True, null=True) phone3 = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) email2 = models.CharField(max_length=255, blank=True, null=True) email3 = models.CharField(max_length=255, blank=True, null=True) website = models.CharField(max_length=255, blank=True, null=True) facebook = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'business_information' class UserBusinessInformation(models.Model): user = models.ForeignKey(AuthUser, models.DO_NOTHING) business = models.ForeignKey(BusinessInformation, models.DO_NOTHING) class Meta: managed = False db_table = 'user_business_information' When I try to access to UserBusinessInformation in my views, I do not manage neither using _set. def school(request, schoolname): school_searched = BusinessInformation.objects.get(name=schoolname) user_linked = school_searched.userbusinessinformation_set.all()
I miss the many to many field: class BusinessInformation(models.Model): business_id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) users = models.ManyToManyField(AuthUser, through='UserBusinessInformation') ... Then, in your view: def school(request, schoolname): school_searched = BusinessInformation.objects.get(name=schoolname) user_linked = school_searched.users.all() Quoting Extra fields on many-to-many relationships django docs: For these situations, Django allows you to specify the model that will be used to govern the many-to-many relationship. You can then put extra fields on the intermediate model. The intermediate model is associated with the ManyToManyField using the through argument to point to the model that will act as an intermediary. Let me finish with a little advice, it is true, 'These are the relevant classes of my app', but you can illustrate this sample with just few fields. Learn about How to create a Minimal, Complete, and Verifiable example
[if you want access a field that’s a ForeignKey, you’ll get the related model object just like] from django.db import models class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField()`enter code here` def __str__(self): return self.name class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField() def __str__(self): return '%s %s' % (self.first_name, self.last_name) class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() def __str__(self): return self.title [you can access like that.... ] b = Book.objects.get(id=50) b.publisher b.publisher.website
Django models and join sql tables
i wanted to try using django instead of having to call my stored procedure on the DB. So i created a new model, taking informations from two differents models class TbMouvementinit(models.Model): id = models.AutoField(db_column='Id', primary_key=True) # Field name made lowercase. dateheurecreat = models.TextField(db_column='DateHeureCreat') # Field name made lowercase. dateheureclot = models.TextField(db_column='DateHeureClot', blank=True, null=True) # Field name made lowercase. id_pesee = models.BigIntegerField(db_column='Id_Pesee') # Field name made lowercase. id_proteine = models.BigIntegerField(db_column='Id_Proteine', blank=True, null=True) # Field name made lowercase. id_humidite = models.BigIntegerField(db_column='Id_Humidite', blank=True, null=True) # Field name made lowercase. id_espece = models.BigIntegerField(db_column='Id_Espece', blank=True, null=True) # Field name made lowercase. id_produit = models.BigIntegerField(db_column='Id_Produit', blank=True, null=True) # Field name made lowercase. id_codeechantillon = models.BigIntegerField(db_column='Id_CodeEchantillon', blank=True, null=True) # Field name made lowercase. id_traitement = models.BigIntegerField(db_column='Id_Traitement', blank=True, null=True) # Field name made lowercase. id_circuit = models.BigIntegerField(db_column='Id_Circuit', blank=True, null=True) # Field name made lowercase. code_source = models.CharField(db_column='Code_Source', max_length=20, blank=True, null=True) # Field name made lowercase. code_destination = models.CharField(db_column='Code_Destination', max_length=20, blank=True, null=True) # Field name made lowercase. nomos = models.CharField(db_column='NomOS', max_length=30, blank=True, null=True) # Field name made lowercase. codesite = models.CharField(db_column='CodeSite', max_length=9, blank=True, null=True) # Field name made lowercase. type_mouvement = models.CharField(db_column='Type_Mouvement', max_length=3, blank=True, null=True) # Field name made lowercase. sous_domaine = models.CharField(db_column='Sous_Domaine', max_length=1, blank=True, null=True) # Field name made lowercase. recolte = models.SmallIntegerField(db_column='Recolte', blank=True, null=True) # Field name made lowercase. espece = models.CharField(db_column='Espece', max_length=9, blank=True, null=True) # Field name made lowercase. code_variete = models.CharField(db_column='Code_Variete', max_length=10, blank=True, null=True) # Field name made lowercase. code_tiers = models.CharField(db_column='Code_Tiers', max_length=9, blank=True, null=True) # Field name made lowercase. num_bl_livreur = models.CharField(db_column='Num_Bl_Livreur', max_length=9, blank=True, null=True) # Field name made lowercase. num_contrat_client = models.IntegerField(db_column='Num_Contrat_Client', blank=True, null=True) # Field name made lowercase. num_oe = models.IntegerField(db_column='Num_OE', blank=True, null=True) # Field name made lowercase. code_transporteur = models.CharField(db_column='Code_Transporteur', max_length=9, blank=True, null=True) # Field name made lowercase. immat_transporteur = models.CharField(db_column='Immat_Transporteur', max_length=10, blank=True, null=True) # Field name made lowercase. poids_charge = models.FloatField(db_column='Poids_Charge', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified poids_vide = models.FloatField(db_column='Poids_Vide', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified code_caract1 = models.CharField(db_column='Code_Caract1', max_length=5, blank=True, null=True) # Field name made lowercase. val_caract1 = models.FloatField(db_column='Val_Caract1', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified code_caract2 = models.CharField(db_column='Code_Caract2', max_length=5, blank=True, null=True) # Field name made lowercase. val_caract2 = models.FloatField(db_column='Val_Caract2', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified code_caract3 = models.CharField(db_column='Code_Caract3', max_length=5, blank=True, null=True) # Field name made lowercase. val_caract3 = models.FloatField(db_column='Val_Caract3', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified code_caract4 = models.CharField(db_column='Code_Caract4', max_length=5, blank=True, null=True) # Field name made lowercase. val_caract4 = models.FloatField(db_column='Val_Caract4', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified code_caract5 = models.CharField(db_column='Code_Caract5', max_length=5, blank=True, null=True) # Field name made lowercase. val_caract5 = models.FloatField(db_column='Val_Caract5', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified code_caract6 = models.CharField(db_column='Code_Caract6', max_length=5, blank=True, null=True) # Field name made lowercase. val_caract6 = models.FloatField(db_column='Val_Caract6', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified code_caract7 = models.CharField(db_column='Code_Caract7', max_length=5, blank=True, null=True) # Field name made lowercase. val_caract7 = models.FloatField(db_column='Val_Caract7', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified code_caract8 = models.CharField(db_column='Code_Caract8', max_length=5, blank=True, null=True) # Field name made lowercase. val_caract8 = models.FloatField(db_column='Val_Caract8', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified code_caract9 = models.CharField(db_column='Code_Caract9', max_length=5, blank=True, null=True) # Field name made lowercase. val_caract9 = models.FloatField(db_column='Val_Caract9', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified code_caract10 = models.CharField(db_column='Code_Caract10', max_length=5, blank=True, null=True) # Field name made lowercase. val_caract10 = models.FloatField(db_column='Val_Caract10', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified code_cel = models.CharField(db_column='Code_Cel', max_length=5, blank=True, null=True) # Field name made lowercase. num_operation = models.IntegerField(db_column='Num_Operation', blank=True, null=True) # Field name made lowercase. datetime2supv = models.CharField(db_column='DateTime2SUPV', max_length=20, blank=True, null=True) # Field name made lowercase. num_lot_supv = models.BigIntegerField(db_column='Num_Lot_SUPV', blank=True, null=True) # Field name made lowercase. user_supv = models.CharField(db_column='User_SUPV', max_length=18, blank=True, null=True) # Field name made lowercase. class TbEspece(models.Model): id = models.AutoField(db_column='Id', primary_key=True) # Field name made lowercase. recolte = models.SmallIntegerField(db_column='Recolte') # Field name made lowercase. groupe = models.CharField(db_column='Groupe', max_length=3) # Field name made lowercase. categorie = models.CharField(db_column='Categorie', max_length=3) # Field name made lowercase. code = models.CharField(db_column='Code', max_length=3) # Field name made lowercase. libelle = models.CharField(db_column='Libelle', max_length=30) # Field name made lowercase. class Meta: managed = False db_table = 'TB_Espece' app_label = 'erp' class ResumeMvtActif(models.Model): mvt = models.ForeignKey(TbMouvementinit) espece = models.ForeignKey(TbEspece) And then call it by using just mouvements = ResumeMvtActif.objects.all() But of course i get a Database error because i don't really have a ResumeMvtActif table. How can i proceed to make this work ? do i have to create an extra table on my DB ? Is there a trick to tell Django that it's not a real table and just a join of two tables ?
Django Restful Framework - Limit Results Based on Role/Group
I'm trying to build an API in Django Rest Framework (Python 3.x). As a requirement from our b2b partners we can only redistribute their content to certain users. Therefore, I'd like to edit the view to only return certain data based on a users group/role in the system. For example, I have the following model: class LocalDeals(models.Model): deal_id = models.IntegerField(db_column='deal_ID', unique=True) # Field name made lowercase. deal_url = models.CharField(db_column='deal_URL', max_length=600) # Field name made lowercase. store_id = models.IntegerField(db_column='store_ID', blank=True, null=True) # Field name made lowercase. store_online_id = models.IntegerField(db_column='storeOnline_ID', blank=True, null=True) # Field name made lowercase. store_chain_id = models.IntegerField(db_column='storeChain_ID', blank=True, null=True) # Field name made lowercase. deal_price = models.FloatField(db_column='dealPrice', blank=True, null=True) # Field name made lowercase. deal_original_price = models.FloatField(db_column='dealOriginalPrice', blank=True, null=True) # Field name made lowercase. deal_title = models.CharField(db_column='dealTitle', max_length=256) # Field name made lowercase. store_name = models.CharField(db_column='storeName', max_length=64, blank=True, null=True) # Field name made lowercase. image_small = models.CharField(db_column='smallImage', max_length=128, blank=True, null=True) # Field name made lowercase. image_large = models.CharField(db_column='largeImage', max_length=128, blank=True, null=True) # Field name made lowercase. store_url = models.CharField(db_column='storeURL', max_length=128, blank=True, null=True) # Field name made lowercase. provider_name = models.CharField(db_column='providerName', max_length=64, blank=True, null=True) # Field name made lowercase. provider_logo = models.CharField(db_column='providerLogo', max_length=128, blank=True, null=True) # Field name made lowercase. user_provider_id = models.IntegerField(db_column='userProvider_ID', blank=True, null=True) # Field name made lowercase. expiration_date = models.DateTimeField(db_column='expirationDate', blank=True, null=True) # Field name made lowercase. create_date = models.DateTimeField(db_column='createDate', blank=True, null=True) # Field name made lowercase. update_date = models.DateTimeField(db_column='updateDate') # Field name made lowercase. yelp_rating = models.FloatField(db_column='yelp_rating',blank=True, null=True) yelp_review_count = models.IntegerField(db_column='yelp_review_count',blank=True, null=True) yelp_rating_img_url = models.CharField(db_column='yelp_rating_img_url',max_length=128, blank=True, null=True) yelp_url = models.CharField(db_column='yelp_url',max_length=128, blank=True, null=True) address1 = models.CharField(db_column='address1',max_length=64, blank=True, null=True) city = models.CharField(db_column='city',max_length=64, blank=True, null=True) state = models.CharField(db_column='state',max_length=32, blank=True, null=True) zip = models.CharField(db_column='zip',max_length=10, blank=True, null=True) country = models.CharField(db_column='country',max_length=32, blank=True, null=True) latitude = models.FloatField(db_column='latitude',blank=True, null=True) longitude = models.FloatField(db_column='longitude',blank=True, null=True) deal_code = models.CharField(db_column='dealCode', max_length=32, blank=True, null=True) # Field name made lowercase. event_date = models.DateTimeField(db_column='eventDate', blank=True, null=True) # Field name made lowercase. is_now_deal = models.IntegerField(db_column='isNowDeal', blank=True, null=True) # Field name made lowercase. business_type = models.IntegerField(db_column='businessType', blank=True, null=True) # Field name made lowercase. scoring_base = models.FloatField(db_column='scoringBase', blank=True, null=True) # Field name made lowercase. deal_type = models.CharField(db_column='dealType', max_length=16, blank=True, null=True) # Field name made lowercase. deal_disclaimer = models.TextField(db_column='dealDisclaimer', blank=True, null=True) # Field name made lowercase. submit_id = models.IntegerField(db_column='submit_ID', blank=True, null=True) # Field name made lowercase. deal_date_time = models.DateField(db_column='deal_datetime',blank=True, null=True) business_type_sub = models.IntegerField(db_column='businessTypeSub', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'local_deals' app_label = 'api' Which is called by the following view and serializer: class LocalDealsViewSet(viewsets.ModelViewSet): """ API endpoint that allows local_deals to be viewed. """ throttle_classes = (UserRateThrottle,) queryset = LocalDeals.objects.all() serializer_class = LocalDealsSerializer class LocalDealsSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = LocalDeals fields = ('deal_id','deal_url','deal_price','deal_original_price','deal_title', 'store_name','image_small','image_large','store_url','provider_name', 'expiration_date','create_date','update_date','address1','city','state', 'zip','country','latitude','longitude','deal_code', 'business_type','business_type_sub','deal_type','deal_date_time',) If the user is not in the auth_group 'admin' (id 1) then I'd like to restrict the results so that it shows all results except where user_provider_id in [1,3]. How can I do this?
You should override get_queryset() method to restrict results based on admin auth group. class LocalDealsViewSet(viewsets.ModelViewSet): """ API endpoint that allows local_deals to be viewed. """ throttle_classes = (UserRateThrottle,) serializer_class = LocalDealsSerializer def get_queryset(self): # check here if 'list' request and user not in admin auth group if self.action == 'list' and self.request.user not in admin auth_group: # exclude results with 'user_provider_id' in [1,3] return LocalDeals.objects.all().exclude(user_provider_id__in=[1,3]) # Otherwise return all results return LocalDeals.objects.all()