Related
The problem is that with this approach, annotate ignores equal amounts, and if you remove distinct=True, then there will be duplicate objects and the difference will not be correct.
In simple words, I want to get the balance of the account by getting the difference between the amount in cash and the amount on receipts for this personal account
queryset = PersonalAccount.objects.select_related(
'apartment', 'apartment__house', 'apartment__section', 'apartment__owner',
).annotate(
balance=
Greatest(Sum('cash_account__sum', filter=Q(cash_account__status=True), distinct=True), Decimal(0))
-
Greatest(Sum('receipt_account__sum', filter=Q(receipt_account__status=True), distinct=True), Decimal(0))
).order_by('-id')
class PersonalAccount(models.Model):
objects = None
class AccountStatus(models.TextChoices):
ACTIVE = 'active', _("Активен")
INACTIVE = 'inactive', _("Неактивен")
number = models.CharField(max_length=11, unique=True)
status = models.CharField(max_length=8, choices=AccountStatus.choices, default=AccountStatus.ACTIVE)
apartment = models.OneToOneField('Apartment', null=True, blank=True, on_delete=models.SET_NULL,
related_name='account_apartment')
class CashBox(models.Model):
objects = None
number = models.CharField(max_length=64, unique=True)
date = models.DateField(default=datetime.date.today)
status = models.BooleanField(default=True)
type = models.BooleanField(default=True)
sum = models.DecimalField(max_digits=10, decimal_places=2)
comment = models.TextField(blank=True)
payment_items = models.ForeignKey('PaymentItems', blank=True, null=True, on_delete=models.SET_NULL)
owner = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL, related_name='owner')
manager = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='manager')
personal_account = models.ForeignKey('PersonalAccount', blank=True, null=True,
on_delete=models.SET_NULL, related_name='cash_account')
receipt = models.ForeignKey('Receipt', blank=True, null=True, on_delete=models.SET_NULL)
class Receipt(models.Model):
objects = None
class PayStatus(models.TextChoices):
PAID = 'paid', _("Оплачена")
PARTIALLY_PAID = 'partially_paid', _("Частично оплачена")
NOT_PAID = 'not_paid', _("Не оплачена")
number = models.CharField(max_length=64, unique=True)
date = models.DateField(default=datetime.date.today)
date_start = models.DateField(default=datetime.date.today)
date_end = models.DateField(default=datetime.date.today)
status = models.BooleanField(default=True)
status_pay = models.CharField(max_length=15, choices=PayStatus.choices, default=PayStatus.NOT_PAID)
sum = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, blank=True)
personal_account = models.ForeignKey('PersonalAccount', blank=True, null=True,
on_delete=models.CASCADE, related_name='receipt_account')
tariff = models.ForeignKey('Tariff', null=True, on_delete=models.CASCADE)
apartment = models.ForeignKey('Apartment', null=True, on_delete=models.CASCADE,
related_name='receipt_apartment')
I need to create a permission that allows the User to see the "Alumno" model, but I only need it to see the records of that model that have the same foreign key as "id_colegio"...
for example, if my User has the foreign key of id_colegio = 1, I need him to be able to see all the records of "Alumno" whose foreign key "id_colegio" = 1
models.py
class User(AbstractUser):
profesor = models.BooleanField(default=False)
rut_user = models.IntegerField(null=True)
id_colegio = models.ForeignKey('Colegio', models.DO_NOTHING, db_column='id_colegio',
null=True,verbose_name="Colegio")
class Alumno(models.Model):
rut_alumno = models.IntegerField(primary_key=True)
dv_alumno = models.CharField(max_length=1)
p_nombre = models.CharField(max_length=15 , verbose_name = "Primer nombre")
s_nombre = models.CharField(max_length=15, blank=True, null=True)
ap_paterno = models.CharField(max_length=15)
ap_materno = models.CharField(max_length=15, blank=True, null=True)
fecha_nac = models.DateField()
genero = models.CharField(max_length=1)
direccion = models.CharField(max_length=25, blank=True, null=True)
nivel_socio = models.CharField(max_length=10)
id_examenes = models.OneToOneField('ExamenCono', models.DO_NOTHING,
db_column='id_examenes')
rut_apoderado = models.ForeignKey('Apoderado', models.DO_NOTHING,
db_column='rut_apoderado')
id_colegio = models.ForeignKey('Colegio', models.DO_NOTHING, db_column='id_colegio')
id_curso = models.ForeignKey('Curso', models.DO_NOTHING, db_column='id_curso')
id_comuna = models.ForeignKey('Comuna', models.DO_NOTHING, db_column='id_comuna')
def __str__(self):
return f"{self.rut_alumno , self.p_nombre , self.ap_paterno}"
class Meta:
managed = True
db_table = 'alumno'
class Colegio(models.Model):
id_colegio = models.IntegerField(primary_key=True,verbose_name="Colegio")
nombre = models.CharField(max_length=20)
telefono = models.IntegerField(blank=True, null=True)
direccion = models.CharField(max_length=25)
id_comuna = models.ForeignKey('Comuna', models.DO_NOTHING, db_column='id_comuna')
I want to add extra-column which is not in my model. And I apply one of the solutions at this site to my project. But it doesn't work properly.
model.py
class Companies(models.Model):
legal_name = models.CharField(max_length=120, blank=True)
co_name = models.CharField(max_length=120, blank=True)
client = models.ForeignKey(Clients, models.SET_NULL, blank=True, null=True)
tel_no = models.CharField(max_length=120, blank=True)
email = models.EmailField(null=True, blank=True)
address = models.TextField(null=True, blank=True)
contact = models.CharField(max_length=250, blank=True)
con_tel_no = models.CharField(max_length=120, blank=True)
entity = models.CharField(max_length=2, null=True)
yearend = models.DateField(null=True, blank=True)
bn = models.CharField(max_length=9)
memo = models.TextField(null=True, blank=True)
slug = models.SlugField(null=True, blank=True)
def t2_due_date(self):
now_year = datetime.date.today().year
if self.entity == 'CO':
yearend_ = DateWidget.decompress(self, self.yearend)
if yearend_[1] > 6:
yearend_[2] = now_year + 1
yearend_[1] -= 6
else:
yearend_[2] = now_year
yearend_[1] += 6
t2_due = DateWidget.compress(self, yearend_)
return t2_due
tables.py
class ScheduleTable(tables.Table):
due_date_col = tables.Column(accessor='t2_due_date', verbose_name='T2 Due Date')
class Meta:
attrs = {"class": "paleblue", "width":"100%"}
fields = ['client','legal_name', 'co_name', 'entity', 'yearend', 'due_date_col']
model = Companies
When I run this program 'due_date_col' is always blank. It seems that the function('t2_due_date) does not go through. Do you have any clue to clear this problem?
As far as I know accessor points to related objects, rather than model's properties, methods etc.
What you can try is to make use of Table.render_{column} as so:
class ScheduleTable(tables.Table):
def render_due_date_col(self, record):
return record.t2_due_date()
See djanog tables official doc for more info.
I've been asked to design a way for people to search through multiple models on criteria they enter and allow them to export any number of fields they select.
Example:
User enters "Teacher" as a term for Job Title and "Google" for a Work Site Location but want to export "Employee ID", "First Name", "Last Name", "Date of Birth"
I'm sure this is possible, but I'm at a complete loss for where to start.
My models (for reference) are here:
import datetime
from django.conf import settings
from django.db import models
from django.db.models import Q
from django.utils import timezone
class Classification(models.Model):
name = models.CharField(max_length=255, blank=False, null=False, verbose_name='Classification Name')
def __str__(self):
return '{}'.format(self.name)
class Meta:
db_table = 'Classification'
verbose_name = 'Classification'
verbose_name_plural = 'Classifications'
class Location(models.Model):
name = models.CharField(max_length=255, blank=False, null=False, verbose_name='Name')
aeries_id = models.CharField(max_length=25, blank=True, null=True, verbose_name='Aeries ID')
county_id = models.CharField(max_length=25, blank=True, null=True, verbose_name='County ID')
def __str__(self):
return '{}'.format(self.name)
class Meta:
db_table = 'Location'
verbose_name = 'Location'
verbose_name_plural = 'Locations'
ordering = ['name']
class Person(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True)
current_identity = models.ForeignKey('PersonIdentity', blank=True, null=True, on_delete=models.SET_NULL, verbose_name='Current Identity', related_name='current_identity')
employee_id = models.CharField(max_length=255, null=False, blank=False, verbose_name='Employee ID')
birthdate = models.DateField(blank=True, null=True, verbose_name='Birthdate')
original_hire_date = models.DateField(blank=True, null=True, verbose_name='Original Hire Date')
def __str__(self):
if self.current_identity is not None:
return '{}'.format(str(self.current_identity))
else:
return "{}".format(self.employee_id)
#property
def current_age(self):
from dateutil.relativedelta import relativedelta
difference_in_years = relativedelta(timezone.now().date(), self.birthdate).years
return difference_in_years
def primary_assignment(self):
return self.jobassignment_set.filter(Q(end_date__gte=timezone.now()) | Q(end_date=None)).order_by('priority')[0]
#property
def display_name(self):
if self.current_identity:
return '{0.first_name} {0.last_name} ({1.employee_id})'.format(self.current_identity, self)
else:
return 'Employee ID {0.employee_id}'.format(self)
#property
def is_certificated(self):
assignments = JobAssignment.objects.filter(Q(end_date__gte=timezone.now()) | Q(end_date=None)).filter(
person=self,
classification__name__icontains="Certificated"
)
return assignments.count() >= 1
class Meta:
db_table = 'Person'
verbose_name = 'Person'
verbose_name_plural = 'People'
class PersonIdentity(models.Model):
person = models.ForeignKey(Person, verbose_name='Person', on_delete=models.CASCADE)
first_name = models.CharField(max_length=50, blank=True, null=True, verbose_name='First Name')
middle_name = models.CharField(max_length=50, blank=True, null=True, verbose_name='Middle Name')
last_name = models.CharField(max_length=50, blank=True, null=True, verbose_name='Last Name')
start_date = models.DateField(blank=False, null=False, default=datetime.date.today, verbose_name='Start Date')
end_date = models.DateField(blank=True, null=True, verbose_name='End Date')
def __str__(self):
first_name = '' if self.first_name is None else self.first_name
last_name = '' if self.last_name is None else self.last_name
if self.middle_name is not None and self.middle_name != '':
return "{} {}. {} ({})".format(first_name, self.middle_name[0], last_name, self.person.employee_id)
else:
return "{} {} ({})".format(first_name, last_name, self.person.employee_id)
def save(self, *args, **kwargs):
change_identity = False
if not self.id:
change_identity = True
super().save(*args, **kwargs)
if change_identity:
self.person.current_identity = self
self.person.save()
class Meta:
db_table = 'PersonIdentity'
verbose_name = 'Person Identity'
verbose_name_plural = 'Person Identities'
ordering = ['end_date', 'last_name', 'first_name']
class Contact(models.Model):
person = models.OneToOneField(Person, on_delete=models.CASCADE, verbose_name='Person')
email_address = models.EmailField(blank=True, null=True, verbose_name='Primary Email')
phone_number = models.CharField(max_length=15, blank=True, null=True, verbose_name='Phone Number')
phone_extension = models.CharField(max_length=255, blank=True, null=True, verbose_name='Phone Extension')
address1 = models.CharField(max_length=255, blank=True, null=True, verbose_name='Address 1')
address2 = models.CharField(max_length=255, blank=True, null=True, verbose_name='Address 2')
city = models.CharField(max_length=255, blank=True, null=True, verbose_name='City')
state = models.CharField(max_length=2, default='CA', blank=True, null=True, verbose_name='State')
postal = models.CharField(max_length=5, blank=True, null=True, verbose_name='Postal Code')
def __str__(self):
return '{}'.format(self.person.current_identity)
class Meta:
db_table = 'Contact'
verbose_name = 'Contact'
verbose_name_plural = 'Contacts'
class Department(models.Model):
department_id = models.CharField(max_length=5, blank=False, null=False, verbose_name='Department ID')
description = models.CharField(max_length=255, blank=False, null=False, verbose_name='Department Description')
def __str__(self):
return '{}'.format(self.description)
class Meta:
db_table = 'Department'
verbose_name = 'Department'
verbose_name_plural = 'Departments'
class Job(models.Model):
name = models.CharField(max_length=255, blank=False, null=False, verbose_name='Name')
code = models.CharField(max_length=255, blank=False, null=False, verbose_name='Code')
def __str__(self):
return '{}'.format(self.name)
class Meta:
db_table = 'Job'
verbose_name = 'Job'
verbose_name_plural = 'Jobs'
class JobPosition(models.Model):
job = models.ForeignKey(Job, blank=True, null=True, verbose_name='Job')
reports_to = models.ForeignKey('JobPosition', blank=True, null=True, verbose_name='Reports To')
name = models.CharField(max_length=255, blank=True, null=True, verbose_name='Name')
number = models.CharField(max_length=255, blank=False, null=False, verbose_name='Number')
def __str__(self):
return '{}'.format(self.name)
class Meta:
db_table = 'JobPosition'
verbose_name = 'Job Position'
verbose_name_plural = 'Job Positions'
class JobAssignment(models.Model):
person = models.ForeignKey(Person, blank=False, null=False, verbose_name='Person')
position = models.ForeignKey(JobPosition, blank=False, null=False, verbose_name='Position')
location = models.ForeignKey(Location, blank=True, null=True, verbose_name='School')
classification = models.ForeignKey(Classification, blank=True, null=True, verbose_name='Classification')
start_date = models.DateField(blank=True, null=True, verbose_name='Start Date')
end_date = models.DateField(blank=True, null=True, verbose_name='End Date')
effective_date = models.DateField(blank=True, null=True, verbose_name='Effective Date')
fte = models.CharField(max_length=10, blank=True, null=True, verbose_name='FTE')
seniority_date = models.DateField(blank=True, null=True, verbose_name='Seniority Date')
last_start_date = models.DateField(blank=True, null=True, verbose_name='Last Start Date')
last_pay_date = models.DateField(blank=True, null=True, verbose_name='Last Pay Date')
entry_date = models.DateField(blank=True, null=True, verbose_name='Position Entry Date')
record_number = models.IntegerField(default=0, verbose_name='Position Record Number')
pay_group = models.CharField(max_length=3, blank=True, null=True, verbose_name='Pay Group')
indicator = models.CharField(max_length=1, blank=True, null=True, verbose_name='Indicator')
full_or_part_time = models.CharField(max_length=1, blank=True, null=True, verbose_name='Full/Part')
standard_hours_per_week = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True, verbose_name='Standard Hours per Week')
pay_status = models.CharField(max_length=1, blank=True, null=True, verbose_name='Pay Status')
comp_rate = models.DecimalField(max_digits=15, decimal_places=6, blank=True, null=True, verbose_name='Comp Rate')
comp_frequency = models.CharField(max_length=10, blank=True, null=True, verbose_name='Comp Freq')
hourly_rate = models.DecimalField(max_digits=10, decimal_places=6, blank=True, null=True, verbose_name='Hrly Rate')
daily_rate = models.DecimalField(max_digits=10, decimal_places=6, blank=True, null=True, verbose_name='Daily Rt')
rate_code = models.CharField(max_length=10, blank=True, null=True, verbose_name='Rate Code')
compensation_rate = models.DecimalField(max_digits=15, decimal_places=6, blank=True, null=True, verbose_name='Compensation Rate')
total_cdays = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True, verbose_name='TOTAL_CDAYS')
teacher_hours = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True, verbose_name='Teacher Hours')
def __str__(self):
return '{} - {}'.format(self.position.name, self.position.number)
#classmethod
def current_assignments(cls):
return cls.objects.filter(Q(end_date__gte=timezone.now()) | Q(end_date=None)).exclude(person__ssn__isnull=True).exclude(person__current_identity__isnull=True).exclude(person__contact__isnull=True)
class Meta:
db_table = 'JobAssignment'
verbose_name = 'Job Assignment'
verbose_name_plural = 'Job Assignments'
ordering = ['location__name', 'person__current_identity__last_name', 'person__current_identity__first_name', 'position__name']
I am attempting to use the Django prefetch_related because of the 1 to many relationship between models LanguageCode and Flag shown below (I am attempting to display the flagIconPath), but I cannot seem to get the views.py code correct and I really need some help!
Here is my views.py form:
from django.shortcuts import render
from app_data.models import RIAchievement
def ri_achievements(request):
qs = RIAchievement.objects.all().prefetch_related("??????", "????????")
return render(request, 'index.html',{'qs': qs})
What code should I be using to replace the ???'s?
Here are the fields I am trying to get the django prefetch_related to display:
(flag) flagiconpath,
(riachievement) riAchievementTypeUserDescription,
(typeachievement) typeAchievementDescriptionIntl,
(languagecode) languageNameNative,
(flag) flagIconPath,
(languagedetail) languageDetailDescription,
(languagedirection) languageDirectionDescription,
(riusersettings) riUserSettingsDisplayMultipleLanguage,
(typeresumestyle) typeResumeStyleNumber,
(auth_user) id.
Here are my relevant models:
class RIAchievement(models.Model):
riAchievementID = models.AutoField(primary_key=True, db_column="riAchievementID")
userLanguageVersionID = models.ForeignKey(UserLanguageVersion, db_column="userLanguageVersionID", related_name="riAchievement_userLanguageVersionID")
typeAchievementID = models.ForeignKey(TypeAchievement, db_column="typeAchievementID", related_name="riAchievement_typeAchievementID")
riAchievementTypeUserDescription = models.CharField(max_length=255, blank=True, null=True, db_column="riAchievementTypeUserDescription")
riAchievementDescription = models.TextField(max_length=2000, db_column="riAchievementDescription")
auth_user_id = models.ForeignKey(auth_user, db_column="auth_user_id", related_name="riAchievement_auth_user_id")
class Meta:
db_table="riAchievement"
class TypeAchievement(models.Model):
typeAchievementID = models.AutoField(primary_key=True, db_column="typeAchievementID")
languageCodeID = models.ForeignKey(LanguageCode, db_column="languageCodeID", related_name="typeAchievement_languageCodeID")
typeAchievementDescriptionIntl = models.CharField(max_length=255, db_column="typeAchievementDescriptionIntl")
typeAchievementDescriptionEng = models.CharField(max_length=255, db_column="typeAchievementDescriptionEng")
typeAchievementAltID = models.IntegerField(db_column="typeAchievementAltID")
class Meta:
db_table="typeAchievement"
class UserLanguageVersion(models.Model):
userLanguageVersionID = models.AutoField(primary_key=True, db_column="userLanguageVersionID")
auth_user_id = models.ForeignKey(auth_user, db_column="auth_user_id", related_name="userLanguageVersion_auth_user_id")
languageCodeID = models.ForeignKey(LanguageCode, db_column="languageCodeID", related_name="userLanguageVersion_languageCodeID")
class Meta:
db_table="userLanguageVersion"
class LanguageCode(models.Model):
languagecodeID = models.AutoField(primary_key=True, db_column="languageCodeID")
languageCodeDescription = models.CharField(max_length=10, db_column="languageCodeDescription")
baseLanguageCode = models.CharField(max_length=10, db_column="baseLanguageCode")
languageNameEng = models.CharField(max_length=255, db_column="languageNameEng")
altLanguageNameEng = models.CharField(max_length=255, blank=True, null=True, db_column="altLanguageNameEng")
languageNameNative = models.CharField(max_length=255, db_column="languageNameNative")
altLanguageNameNative = models.CharField(max_length=255, blank=True, null=True, db_column="altLanguageNameNative")
iso639_1 = models.CharField(max_length=10, blank=True, null=True, db_column="iso639_1")
iso639_2T = models.CharField(max_length=10, db_column="iso639_2T")
iso639_2B = models.CharField(max_length=10, db_column="iso639_2B")
iso639_X = models.CharField(max_length=10, db_column="iso639_X")
languageDirectionID = models.ForeignKey(LanguageDirection, default=1, db_column="languageDirectionID", related_name="languageCode_languageDirectionID")
class Meta:
db_table="languageCode"
class Flag(models.Model):
flagID = models.AutoField(primary_key=True, db_column="flagID")
languageCodeID = models.ForeignKey(LanguageCode, db_column="languageCodeID", related_name="flag_languageCodeID")
flagIconPath = models.CharField(max_length=255, db_column="flagIconPath")
flagDescription = models.CharField(max_length=255, db_column="flagDescription")
flagInformation = models.CharField(max_length=255, db_column="flagInformation")
class Meta:
db_table="flag"
class auth_user(models.Model):
auth_user_id = models.AutoField(primary_key=True, db_column="id")
username = models.CharField(max_length=30, unique=True, db_column="username")
first_name = models.CharField(max_length=30, db_column="first_name")
last_name = models.CharField(max_length=30, db_column="last_name")
email = models.CharField(max_length=75, db_column="email")
password = models.CharField(max_length=128, db_column="password")
is_staff = models.BooleanField(db_column="is_staff")
is_active = models.BooleanField(db_column="is_active")
is_supervisor = models.BooleanField(db_column="is_supervisor")
last_login = models.DateTimeField(db_column="last_login")
date_joined = models.DateTimeField(db_column="date_joined")
class Meta:
db_table="auth_user"
class RIUserSettings(models.Model):
riUserSettingsID = models.AutoField(primary_key=True, unique=True, db_column="riUserSettingsID")
riUserSettingsPrimaryLanguageCodeID = models.ForeignKey(LanguageCode, db_column="riUserSettingsPrimaryLanguageCodeID", related_name="riUserSettings_riUserSettingsPrimaryLanguageCodeID")
riUserSettingsDisplayPrimaryLanguage = models.BooleanField(default=False, db_column="riUserSettingsDisplayPrimaryLanguage")
riUserSettingsDisplayMutipleLanguage = models.BooleanField(default=False, db_column="riUserSettingsDisplayMutipleLanguage")
riUserSettingsDisplaySingleLanguage = models.BooleanField(default=False, db_column="riUserSettingsDisplaySingleLanguage")
riUserSettingsPrimaryVirtualKeyboardLanguageVersionID = models.ForeignKey(UserLanguageVersion, db_column="riUserSettingsPrimaryVirtualKeyboardLanguageVersionID", related_name="riUserSettings_riUserSettingsPrimaryVirtualKeyboardLanguageVersionID")
riUserSettingsDisplayPrimaryVirtualKeyboard = models.BooleanField(default=False, db_column="riUserSettingsDisplayPrimaryVirtualKeyboard")
riUserSettingsDisplayRIFormattingPreview = models.BooleanField(default=True, db_column="riUserSettingsDisplayRIFormattingPreview")
typeResumeStyleID = models.ForeignKey(TypeResumeStyle, db_column="typeResumeStyleID", related_name="riUserSettings_typeResumeStyleID")
auth_user_id = models.ForeignKey(auth_user, db_column="auth_user_id", related_name="riUserSettings_auth_user_id")
class Meta:
db_table="riUserSettings"
class LanguageDetail(models.Model):
languageDetailID = models.AutoField(primary_key=True, unique=True, db_column="languageDetailID")
languageCodeID = models.ForeignKey(LanguageCode, db_column="languageCodeID", related_name="languageDetail_languageCodeID")
nativeLanguageCodeID = models.ForeignKey(LanguageCode, db_column="nativeLanguageCodeID", related_name="languageDetail_nativeLanguageCodeID")
languageDetailDescriptionIntl = models.CharField(max_length=255, db_column="languageDetailDescriptionIntl")
languageDetailDescriptionEng = models.CharField(max_length=255, db_column="languageDetailDescriptionEng")
languageDetailDescriptionNative = models.CharField(max_length=255, db_column="languageDetailDescriptionNative")
displayCapitaliseCountryName = models.BooleanField(default=False, db_column="displayCapitaliseCountryName")
languageDirectionID = models.ForeignKey(LanguageDirection, default=1, db_column="languageDirectionID", related_name="languageDetail_languageDirectionID")
flagID = models.ForeignKey(Flag, db_column="flagID", related_name="languageDetail_FlagID")
languageDetailAltID = models.IntegerField(db_column="languageDetailAltID")
class Meta:
db_table="languageDetail"
class LanguageDirection(models.Model):
languageDirectionID = models.AutoField(primary_key=True, db_column="languageDirectionID")
languageDirectionDescription = models.CharField(max_length=20, db_column="languageDirectionDescription")
languageDirDescription = models.CharField(max_length=20, db_column="languageDirDescription")
textAlign = models.CharField(max_length=20, db_column="textAlign")
oppositeLanguageDirectionDescription = models.CharField(max_length=20, db_column="oppositeLanguageDirectionDescription")
oppositeLanguageDirDescription = models.CharField(max_length=20, db_column="oppositeLanguageDirDescription")
oppositeTextAlign = models.CharField(max_length=20, db_column="oppositeTextAlign")
class Meta:
db_table="languageDirection"
class TypeResumeStyle(models.Model):
typeResumeStyleID = models.AutoField(primary_key=True, db_column="typeResumeStyleID")
languageCodeID = models.ForeignKey(LanguageCode, db_column="languageCodeID", related_name="typeResumeStyle_languageCodeID")
typeResumeStyleNumber = models.IntegerField(db_column="typeResumeStyleNumber")
typeResumeStyleNameIntl = models.CharField(max_length=255, db_column="typeResumeStyleNameIntl")
typeResumeStyleNameEng = models.CharField(max_length=255, db_column="typeResumeStyleNameEng")
typeResumeStyleDescriptionIntl = models.CharField(max_length=255, db_column="typeResumeStyleDescriptionIntl")
typeResumeStyleDescriptionEng = models.CharField(max_length=255, db_column="typeResumeStyleDescriptionEng")
class Meta:
db_table="typeResumeStyle"
Aagh, my eyes. Please give your fields suitably Pythonic names. Especially since you're already using the db_column attribute, you can keep your DB as it is and give your fields names we can actually read.
In particular, your ForeignKey fields shouldn't be called fooId: the underlying database field is an ID, but the field is not, it's a reference to the actual FK model.
To answer your question though, all the FKs you mention are forward references, not backwards. So you need to use select_related, not prefetch_related, here.