How to make a one to many relationship in Django/Mysql? - django

I am trying to understand how to make a one to many relationship in Django/Mysql?
Here is models.py (code below)
class Flora2Estado(models.Model):
estado = models.OneToOneField(Estados, models.DO_NOTHING, primary_key=True)
especie = models.ForeignKey('Listaflor', models.DO_NOTHING)
class Meta:
managed = False
db_table = 'flora2estado'
unique_together = (('estado', 'especie'),)
class Listaflor(models.Model):
especie = models.OneToOneField(Flora2Estado, models.DO_NOTHING, primary_key=True)
familia = models.ForeignKey(Familia, models.DO_NOTHING, blank=True, null=True)
nome = models.CharField(db_column='especie', max_length=255, blank=True, null=True) # Field renamed because of name conflict.
class Meta:
managed = False
db_table = 'listaflor'
class Estados(models.Model):
estado_id = models.AutoField(primary_key=True)
estado_nome = models.CharField(max_length=100, blank=True, null=True)
class Meta:
managed = False
db_table = 'estados

I think that what you want to do is a Many2Many relation between Listaflor and Estados through another class called Flora2Estado. Django M2M relation
class Estados(models.Model):
estado_id = models.AutoField(primary_key=True)
estado_nome = models.CharField(max_length=100, blank=True, null=True)
class Meta:
managed = False
db_table = 'estados'
class Listaflor(models.Model):
especie_id = models.AutoField(primary_key=True)
nome = models.CharField(db_column='especie', max_length=255, blank=True, null=True)
estados = models.ManyToManyField(Estados, through='Flora2Estado')
class Meta:
managed = False
db_table = 'listaflor'
class Flora2Estado(models.Model):
estado = models.ForeignKey(Estados, on_delete=models.DO_NOTHING)
especie = models.ForeignKey(Listaflor, on_delete=models.DO_NOTHING)
class Meta:
managed = False
db_table = 'flora2estado'
unique_together = (('estado', 'especie'),)

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

Nested Serializers with multiple tables not working

I have the below tables in models.py.
class ProductLine(models.Model):
availability = models.CharField(max_length=20, blank=True, null=True)
series = models.CharField(max_length=20, blank=True, null=True)
model = models.CharField(max_length=20, blank=True, null=True)
class Meta:
db_table = "product_line"
class DriveType(models.Model):
drive_name = models.CharField(max_length=20, blank=True, null=True)
product_line = models.ForeignKey(ProductLine, related_name="drive_type")
class Requirements(models.Model):
performance_unit = models.CharField(max_length=100, blank=True, null=True)
drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True)
class Meta:
db_table = "requirements"
class WorkloadType(models.Model):
workload_type_options = models.CharField(max_length=50, blank=True, null=True)
drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True)
class Meta:
db_table = "workload_type"
I have below serializers:
class WorkloadTypeSerializer(serializers.ModelSerializer):
class Meta:
model = WorkloadType
fields = "__all__"
class RequirementsSerializer(serializers.ModelSerializer):
class Meta:
model = Requirements
fields = "__all__"
class DriveTypeSerializer(serializers.ModelSerializer):
requirements = RequirementsSerializer(many = False, read_only = True)
workload_type = WorkloadTypeSerializer(many=False,read_only=True)
class Meta:
model = DriveType
fields = (
"drive_name", "available_drive_type", "capacity", "raid_type", "raid_size", "workload", "workload_percentage",
"raid_groups", "compression", "compression_value","requirements","workload_type")
class ProductLineSerializer(serializers.ModelSerializer):
drive_type = DriveTypeSerializer(many=True, read_only=True)
class Meta:
model = ProductLine
fields = ('availability','series','model','drive_type')
In my views I have this:
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
def get_queryset(self):
return ProductLine.objects.filter(id=self.kwargs.get("pk"))
serializer_class = ProductLineSerializer
I am getting output as below :
{
"availability": "Current",
"series": "3000",
"model": "2000",
"drive_type": [
{
"drive_name": "drive1",
"requirements": {
"drive_type": 2,
"performance_unit": "by_iops",
}
}
]
}
Why I am not able to see WorkLoadType tables data in json where as I am able to see Requirements data . I don't even see the field in json. Nested serializers only support a single relation tables
Answering my own question. Have to use related_name in the models for reverse relationship.
class Requirements(models.Model):
performance_unit = models.CharField(max_length=100, blank=True, null=True)
drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True,related_name=requirements)
class Meta:
db_table = "requirements"
class WorkloadType(models.Model):
workload_type_options = models.CharField(max_length=50, blank=True, null=True)
drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True,related_name=workload_type)

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

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.

Django ListView with multiple models

How do I create a list view that calls multiple classes/models from my model.py file?
I have created my project, and app and my models. The models use a one-to-many relationship.
I am able to create a listview based on calling a single model, but not using multiple models (in this scenario 7 models).
Here are the models I want to call, with the the required model values that I want displayed in the listview are denoted by **:
class TypeAchievement(models.Model):
typeAchievementID = models.AutoField(primary_key=True, db_column="TypeAchievementID")
languageCodeID = models.ForeignKey(LanguageCode, db_column="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 RIAchievement(models.Model):
riAchievementID = models.AutoField(primary_key=True, db_column="RIAchievementID")
userLanguageVersionID = models.ForeignKey(UserLanguageVersion, db_column="UserLanguageVersionID")
typeAchievementID = models.ForeignKey(TypeAchievement, db_column="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")
class Meta:
db_table="RIAchievement"
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")
languageCodeID = models.ForeignKey(LanguageCode, db_column="LanguageCodeID")
class Meta:
db_table="UserLanguageVersion"
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 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")
class Meta:
db_table="LanguageCode"
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 Flag(models.Model):
flagID = models.AutoField(primary_key=True, db_column="FlagID")
languageCodeID = models.ForeignKey(LanguageCode, db_column="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"
You can get linked objects from the main one. In your case - iterate over list of RIAchievement and get other data as {{ riachievement.userLanguageVersionID.languageCodeID.languageDirectionID.textAlign }}
P.S. Also, please format code according to pep8 even it is autogenerated from the database.