create custom view permission in django - 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')

Related

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

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

Accessing model through other model via django queryset

I need to access columns in particular table through foreign keys in another table. I wrote it in SQL, but how it will be in queryset language?
This is models.py
class carModel(models.Model):
id_car_model = models.IntegerField(primary_key=True)
id_car_mark = models.ForeignKey(carMark,on_delete=models.CASCADE)
name = models.CharField(max_length=255)
date_create = models.IntegerField(max_length=10,null=True)
date_update = models.IntegerField(max_length=10,null=True)
id_car_type = models.ForeignKey(carType,on_delete=models.CASCADE)
name_rus = models.CharField(max_length=255,null=True)
class CarParts(models.Model):
id_catalog = models.IntegerField(primary_key=True)
manufacturer = models.CharField(max_length=200,blank=True, null=True)
vendor_code = models.IntegerField(blank=True, null=True)
subgroup = models.CharField(max_length=200,blank=True, null=True)
title = models.CharField(max_length=200,blank=True, null=True)
side = models.CharField(max_length=200,blank=True, null=True)
description = models.CharField(max_length=200,blank=True, null=True)
model = models.CharField(max_length=200,blank=True, null=True)
trade_mark = models.CharField(max_length=200,blank=True, null=True)
original_number = models.CharField(max_length=200,blank=True, null=True)
request = models.CharField(max_length=200,blank=True, null=True)
price = models.IntegerField(blank=True, null=True)
sum = models.IntegerField(blank=True, null=True)
availability = models.CharField(max_length=200,blank=True, null=True)
class interimTable(models.Model):
id_interim = models.IntegerField(primary_key=True)
description = models.CharField(max_length=100,null=True)
id_catalog=models.ForeignKey(CarParts, on_delete=models.CASCADE)
id_car_model = models.ForeignKey(carModel,on_delete=models.CASCADE)
This is SQL request, that is successful. I need same thing, but like querySet, to use it in further code.
Select title,side,price
from carinfo_carparts,carinfo_interimtable,carinfo_carmodel
where id_catalog = carinfo_interimtable.id_catalog_id
and carinfo_carmodel.id_car_model = carinfo_interimtable.id_car_model_id
and carinfo_carmodel.name='Civic';
this is the result
Try this,
CarParts.objects.filter(interimtable__id_car_model__name='Civic').values('title', 'side', 'price')

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.

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.