How to make import using unique_together? - django

I need to make an import using not only the id field but also the brand field. So that products can exist with the same ID but a different brand
class Part(models.Model):
brand = models.CharField('Производитель', max_length=100, blank=True, default='Нет производителя')
id = models.CharField('Артикул', max_length=100, unique=True, primary_key=True)
name = models.CharField('Название', max_length=100, blank=True, default='Нет имени')
description = models.TextField('Комментарий', blank=True, max_length=5000, default='Нет описания')
analog = models.ManyToManyField('self', through='ContactConnection',blank=True, related_name='AnalogParts')
analog = models.ManyToManyField('self',blank=True, related_name='AnalogParts')
images = models.FileField('Главное изображение', upload_to = 'parts/', blank=True)
images0 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True)
images1 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True)
images2 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True)
def __str__(self):
return str(self.id)
return self.name
class Meta:
verbose_name = 'Запчасть'
verbose_name_plural = 'Запчасти'
unique_together = [['id', 'brand']]
class PartConnection(models.Model):
to_part = models.ForeignKey(Part, on_delete=models.CASCADE, related_name='to_parts')
from_part = models.ForeignKey(Part, on_delete=models.CASCADE, related_name='from_parts')

Related

create custom view permission in django

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

How can I allow a user to filter models dynamically and export only certain fields?

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']

Display attribute of a foreign key in a form in Django

I have 2 models
class Task(models.Model):
taskid = models.AutoField(primary_key=True,default = increment_booking_number)
projectcode = models.ForeignKey('Project', models.DO_NOTHING, db_column='projectid')
taskname = models.CharField(max_length=100)
taskdescription = models.TextField(max_length=500, blank=True, null=True)
and
class Project(models.Model):
projectid = models.AutoField(primary_key=True,default = increment_project_number)
teamcode = models.ForeignKey('Teammember', models.DO_NOTHING, db_column='teamcode', blank=True, null=True)
projectname = models.CharField(max_length=40, blank=True, null=True)
projectdescription = models.CharField(max_length=255, blank=True, null=True)
and in my form I want to display the projectname but it displays "Object object"
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = (
'projectcode',
'taskname',
'taskdescription',)
I tried something like this: projectname = forms.ModelChoiceField(queryset = Project.objects.all()) but it's not good...
Any advice please?
class Project(models.Model):
projectid = models.AutoField(primary_key=True,default = increment_project_number)
teamcode = models.ForeignKey('Teammember', models.DO_NOTHING, db_column='teamcode', blank=True, null=True)
projectname = models.CharField(max_length=40, blank=True, null=True)
projectdescription = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
return self.projectname
add str method to your model will fine.more info here
Well, you have to add str() method at the end of your Task Model
class Task(models.Model):
taskid = models.AutoField(primary_key=True,default = increment_booking_number)
projectcode = models.ForeignKey('Project', models.DO_NOTHING, db_column='projectid')
taskname = models.CharField(max_length=100)
taskdescription = models.TextField(max_length=500, blank=True, null=True)
#add this
def __str__(self):
return self.projectname
str() method allows us to return a nice, human-readable representation of the model for more info refer to documentation of str() method
Note:
you have to add this code above the Task Model Class in case you are using Python2:
#python_2_unicode_compatible # only if you need to support Python 2
class Task(models.Model):
taskid = models.AutoField(primary_key=True,default = increment_booking_number)
projectcode = models.ForeignKey('Project', models.DO_NOTHING, db_column='projectid')
taskname = models.CharField(max_length=100)
taskdescription = models.TextField(max_length=500, blank=True, null=True)
def __str__(self):
return self.projectname
def __unicode__(self)
return self.__str__()

Django - edit many-to-many inline

I have following model
class Day(models.Model):
date = models.DateField(auto_now=False, auto_now_add=False)
price = models.FloatField()
payment_method = models.CharField(max_length = 200, blank=True)
payment_date = models.CharField(max_length=200, blank=True)
room = models.ForeignKey(Room, null=True, blank=True, verbose_name='Номер', on_delete=models.CASCADE)
def __unicode__(self):
return str(self.date)
class Reservation(models.Model):
start = models.DateField(verbose_name='Заезд', auto_now=False, auto_now_add=False, blank=False)
end = models.DateField(verbose_name='Выезд', auto_now=False, auto_now_add=False, blank=False)
check_in_time = models.TimeField(verbose_name='Время заезда', blank=False)
check_out_time = models.TimeField(verbose_name='Время выезда', blank=False)
has_refund = models.BooleanField(verbose_name='Возвратная бронь', default=True)
payed = models.BooleanField(verbose_name='Оплачено', default=False)
reserved_days = models.ManyToManyField(Day, blank=False)
additional_services = models.ManyToManyField(AdditionalService)
guest_name = models.CharField(verbose_name='Имя гостя', max_length=200, blank=True)
reservation_number = models.CharField(verbose_name='Номер брони', max_length=200, blank=True)
What I want is to have ability to edit Day on Reservation page
I try the following as in the django docs
class ReservedDaysInline(admin.TabularInline):
model = Reservation
extra = 1
class ReservationAdmin(admin.ModelAdmin):
inlines = (ReservedDaysInline,)
class DayAdmin(admin.ModelAdmin):
inline = (ReservedDaysInline,)
admin.site.register(Reservation, ReservationAdmin)
admin.site.register(Day, DayAdmin)
But it doesnt work.
What am I doing wrong ?
Try this from doc
class ReservedDaysInline(admin.TabularInline):
model = Reservation.reserved_days.through
extra = 1
class ReservationAdmin(admin.ModelAdmin):
inlines = (ReservedDaysInline,)
exclude = ('reserved_days',)

How to get Django prefetch_related working?

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.