RecursionError : maximum recursion depth exceeded while calling a Python object - python

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.

Related

Creating an Inline Formset - Foreign Key Issue

I have the following 2 models that I want to use in a form set. I'm not sure what I've got wrong
models.py
class AppTradingPartnerTrp(models.Model):
id_trp = models.AutoField(primary_key=True)
tpid_trp = models.CharField(max_length=50, blank=True, null=True)
name_trp = models.CharField(max_length=50)
description_trp = models.CharField(max_length=100, blank=True, null=True)
idtrn_trp = models.ForeignKey('AppTransmissionTrn', models.DO_NOTHING, db_column='idtrn_trp', blank=True, null=True)
class AppCustomerTpRel(models.Model):
id_rel = models.AutoField(primary_key=True)
idcst_rel = models.ForeignKey(AppCustomerCst, models.DO_NOTHING, db_column='idcst_rel')
idtrp_rel = models.ForeignKey(AppTradingPartnerTrp, models.DO_NOTHING, db_column='id_trp')
cust_vendor_rel = models.CharField(max_length=50, blank=True, null=True)
sender_id_rel = models.CharField(max_length=50, blank=True, null=True)
old_vendor_rel = models.CharField(max_length=50, blank=True, null=True)
vendor_name_rel = models.CharField(max_length=50, blank=True, null=True)
category_rel = models.CharField(max_length=50, blank=True, null=True)
And here is where I'm trying to create the formset:
forms.py
CstVendorNoFormSet = inlineformset_factory(AppCustomerTpRel, AppTradingPartnerTrp, exclude=())
However when I do runserver I'm getting:
ValueError: 'AppTradingPartnerTrp' has no ForeignKey to 'AppCustomerTpRel'.
It looks like you've got your ForeignKey relationships the wrong way round.
Side note: I noticed that in your 'AppTradingPartnerTrp' model, for the idtrn_trp FK field, you have got 'AppTransmissionTrn' as a string, I think it should be AppTransmissionTrn without the apostrophes.
You have reversed the model order
inlineformset_factory(parent_model, model, ... )
Parent model is AppTradingPartnerTrp as it has multiple AppCustomerTpRel (foreign key) so
CstVendorNoFormSet = inlineformset_factory(AppTradingPartnerTrp, AppCustomerTpRel, exclude=())

Trouble using an Oracle View in Models.py

My group and I are attempting to rewrite our website. We are keeping an Oracle database back-end, and rewriting the front-end with Python Django.
No problem connecting to Oracle, or accessing the datatables. Now I'm trying to add an Oracle view to the models.py, and I can't get it to work.
I googled this question with many results, so I know it is possible and apparently common, but I can't get it to work.
All I've done so far is add the class to models.py. We are using PhCharm as our IDE.
When I try to access the data using the Python Console, I can import the class, but when I try to load the QuerySet I get the error "Unable to get repr for " in the result window.
Does anyone see something I'm missing from my model?
Here is the model:
class LawBillRoleActionInfoView(LawBaseClass):
combo_id = models.AutoField(primary_key=True)
rltp_role_cd = models.CharField(max_length=2, blank=True)
bill_dft_no = models.CharField(max_length=6, blank=True)
session_id = models.IntegerField(blank=True, null=True)
ebrl_appl_seq = models.IntegerField(blank=True, null=True)
enty_id_seq = models.IntegerField(blank=True, null=True)
lst_nm = models.CharField(max_length=100, blank=True)
fst_nm = models.CharField(max_length=40, blank=True)
mi = models.CharField(max_length=1, blank=True)
entity = models.CharField(max_length=145, blank=True, null=True)
prtydist = models.CharField(max_length=11, blank=True, null=True)
blac_appl_seq = models.IntegerField(blank=None, null=True)
role_descr = models.CharField(max_length=80, blank=True)
shr_ttl = models.CharField(max_length=80, blank=True)
lmt_ind = models.CharField(max_length=1, blank=True)
bltp_bill_typ_cd = models.CharField(max_length=2, blank=True)
bill_no = models.IntegerField(blank=True, null=True)
actn_descr = models.CharField(max_length=80, blank=True)
actn_dt = models.DateField(blank=True, null=True)
sess_law_chpt_no = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'law_bill_role_action_info_vw'
unique_together = (('bill_dft_no', 'rltp_role_cd', 'session_id'),)
app_label = 'laws'
Here are the commands I am running from the Python Console:
from laws.models import LawBillRoleActionInfoView
bill_qs = LawBillRoleActionInfoView.objects.all()
Here is the LawBaseClass:
Base Class
class LawBaseClass(models.Model):
"""
Base class
"""
created_by = models.CharField(max_length=30, blank=True, null=True)
dtm_created = models.DateField(blank=True, null=True)
mod_by = models.CharField(max_length=30, blank=True, null=True)
dtm_mod = models.DateField(blank=True, null=True)
class Meta:
managed = False
abstract = True

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

For loop issue writing multiple lines to database

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.

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()

Categories

Resources