ForeignKey instance error Exception at Django - django

I get this error when I register the Personel form; "Exception Value: Cannot assign "5": "db_PERSONEL.db_departman" must be a "db_DEPARTMAN" instance. ".
Thanks.
departman_app.model.py
from django.db import models
class db_DEPARTMAN(models.Model):
id = models.AutoField(primary_key=True, editable=False)
db_departmanAdi = models.CharField(max_length = 50)
def __unicode__(self):
return u'%s' % (self.db_departmanAdi)
personel_app.models.py
from django.db import models
from departman.models import db_DEPARTMAN
class db_PERSONEL(models.Model):
id = models.AutoField(primary_key=True, editable=False)
db_personelAdi = models.CharField(max_length = 50)
db_departmanAdi = models.ForeignKey(db_DEPARTMAN, on_delete=models.DO_NOTHING, related_name="tags")
def __unicode__(self):
return u'%s' % (self.db_departmanAdi)
personel_app.personelform.py
from django import forms
from personel.models import db_PERSONEL
class personelForm(forms.ModelForm):
class Meta:
model=db_PERSONEL
#fields="__all__"
fields = [
'db_personelAdi',
'db_departmanAdi',
]
form = personelForm()
form.base_fields['db_personelAdi'] = forms.CharField(label='Personel Adı:', max_length=50, widget=forms.TextInput(attrs={'class': 'form-control'}))
form.base_fields['db_departmanAdi'] = forms.IntegerField(label='Deaprtman Adı:', widget=forms.TextInput(attrs={'class': 'form-control'}))

Related

How to update fields on import Django?

I need to update fields on import for ManyToMany bulk editing.
When importing, now I can only add products, because when I try to add already existing fields, I get a message about already existing IDs.
How can I update products using import?
admin.py
class ProductResource(resources.ModelResource):
class Meta:
model = Part
class PartAdmin(ImportExportActionModelAdmin):
resource_class = ProductResource
filter_horizontal = ('analog',)
admin.site.register(Part, PartAdmin)
models.py
class Part(models.Model):
brand = models.CharField('Производитель', max_length=100)
number = models.CharField('Артикул', max_length=100, unique=True)
name = models.CharField('Название', max_length=100)
description = models.TextField('Комментарий', blank=True, max_length=5000)
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.brand + " " + self.number + " " + self.name)
return self.name
from django.contrib import admin
from .models import *
from import_export.admin import ImportExportActionModelAdmin
from import_export import resources
from import_export import fields
from import_export.widgets import ForeignKeyWidget
class ProductResource(resources.ModelResource):
#category = fields.Field(column_name='Артикул', attribute='number')
class Meta:
model = Part
import_id_field = 'number'
import_id_fields = ('number',)
def skip_row(self, instance, original):
original_id_value = getattr(original, self._meta.import_id_field)
instance_id_value = getattr(instance, self._meta.import_id_field)
if original_id_value != instance_id_value:
return True
if not self._meta.skip_unchanged:
return False
for field in self.get_fields():
try:
if list(field.get_value(instance).all()) != list(field.get_value(original).all()):
return False
except AttributeError:
if field.get_value(instance) != field.get_value(original):
return False
return True
admin.site.register(Kits)
class PartAdmin(ImportExportActionModelAdmin):
resource_class = ProductResource
filter_horizontal = ('analog',)
admin.site.register(Part, PartAdmin)
#class PartAdmin(admin.ModelAdmin):
# filter_horizontal = ('analog',)
#admin.site.register(Part, PartAdmin)

Adding Foreign Key to Django Import Export

I am trying to import data from a csv using Django_Import Export. I saw other SO posts but they are not helping. Below are the models
Models.py
class TblSubject(amdl.AagamBaseModel):
subject_id = models.AutoField(primary_key=True)
subject_name = models.CharField(max_length=20)
standard = models.ForeignKey('TblStandard', models.DO_NOTHING)
remembrance_credit = models.IntegerField(default=40)
applied_knowledge_credit = models.IntegerField(default=30)
understanding_credit = models.IntegerField(default=30)
subject_credit = models.IntegerField(default=100)
class Meta:
db_table = 'tblsubject'
def __str__(self):
return f'{self.subject_name}'
class SubjectChapter(amdl.AagamBaseModel):
subject_chapter_id = models.AutoField(primary_key=True)
subject = models.ForeignKey('TblSubject', on_delete=models.CASCADE)
chapter_id = models.IntegerField()
chapter_name = models.CharField(max_length=150)
remembrance_credit = models.IntegerField()
applied_knowledge_credit = models.IntegerField()
understanding_credit = models.IntegerField()
chapter_credit = models.IntegerField()
class Meta:
db_table = 'subject_chapter'
def __str__(self):
return f'{self.chapter_id} {self.chapter_name} : {self.subject}'
Here is the admin.py
from django.contrib import admin
from import_export import resources, fields
from import_export.widgets import ForeignKeyWidget
from .models import SubjectChapter, TblSubject
from import_export.admin import ImportExportModelAdmin
class SubjectChapterResource(resources.ModelResource):
class Meta:
model = SubjectChapter
import_id_fields = ('subject_chapter_id',)
subject = fields.Field(
column_name='subject_name',
attribute='subject_name',
widget=ForeignKeyWidget(TblSubject, 'subject_id'))
class SubjectChapterAdmin(ImportExportModelAdmin):
resource_class = SubjectChapterResource
admin.site.register(SubjectChapter, SubjectChapterAdmin)
And i am getting this below error
I am inserting data for SUBJECTCHAPTER from csv where the SUBJECT column is a foreign key from TBLSUBJECT and it contains the name of the TBLSUBJECT.
Change this
class SubjectChapterResource(resources.ModelResource):
class Meta:
model = SubjectChapter
import_id_fields = ('subject_chapter_id',)
subject = fields.Field(
column_name='subject_name',
attribute='subject_name',
widget=ForeignKeyWidget(TblSubject, 'subject_name'))
From subject_id to subject_name

how to count total student according to 'course' model in django

I am trying to count the number of the student according to CourseMasterModel.
I did it in MySQL, but I want to in Django.
select cn.course_name,count(st.id) from course_master
cn,semister_master sem,division_master di,student_profile st where
st.division_id = di.id and di.semister_id = sem.id and sem.course_id =
cn.id GROUP BY cn.course_name;
class CourseMasterModel(models.Model):
course_name = models.CharField(max_length=20,unique=True)
total_semister = mod`enter code here`els.SmallIntegerField()
class Meta:
db_table = "course_master"
verbose_name_plural = 'Course (Department)'
verbose_name = "Course"
def __str__(self):
return self.course_name
class SemisterMasterModel(models.Model):
semister = models.SmallIntegerField()
total_div = models.SmallIntegerField()
course = models.ForeignKey(CourseMasterModel,on_delete=models.PROTECT)
class Meta:
db_table = "Semister_master"
verbose_name_plural = 'Semister'
verbose_name = "semister"
def __str__(self):
return "%s - %d" %(self.course.course_name,self.semister)
class DevisionMasterModel(models.Model):
div_name = models.CharField(max_length=2)
semister = models.ForeignKey(SemisterMasterModel,on_delete=models.CASCADE)
class Meta:
db_table = "division_master"
verbose_name_plural = 'Division'
verbose_name = "Division"
def __str__(self):
return "%s - %s - %s"%(self.semister.course.course_name,self.semister.semister,self.div_name)
class StudentProfileModel(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="profile")
division = models.ForeignKey('core.DevisionMasterModel',on_delete=models.CASCADE,verbose_name="Course / Semister / Division")
roll_no = models.IntegerField()
enrollment_no = models.IntegerField(unique=True, error_messages={'unique':"This enrollment number has already been registered."})
def __str__(self):
return self.user.username
class Meta:
db_table = "Student_Profile"
You can annotate your CourseMasterModel, like:
from django.db.models import Count
CourseMasterModel.objects.annotate(
nstudents=Count('semistermastermodel__devisionmastermodel__studentprofilemodel')
)
The CourseMasterModels that arise from this QuerySet have an extra attribute .nstudents that contains the number of related StudentProfileModels.
Note: usually the names of Django models have no Model suffix, so CourseMaster instead of CourseMasterModel.
In case you rename the models, the query is:
from django.db.models import Count
CourseMasterModel.objects.annotate(
nstudents=Count('semistermaster__devisionmaster__studentprofile')
)

QuerySet in Django - returns exception

I am trying to understand how exactly query works on Django, i followed the tutorials it´s not working I am not sure what i am doing wrong.
When I run
BeneficientePagar.objects.filter(nome__contains="Joao Pedro")
it returns
"Choices are %s" %s (name, ",".join(available))) django.core.exceptions.FieldError: Cannot resolve keyword "nome into field. Choices are: ID, beneficiente, beneficiente_id,join, join_id, moeda
from django.db import models
# Create your models here.
class Moeda(models.Model):
moeda_ficticia = models.FloatField()
class Join(models.Model):
nome = models.CharField(max_length=150)
nascimento = models.DateField()
cpf = models.IntegerField(primary_key=True)
endereco = models.CharField(max_length=150)
email = models.EmailField()
def __str__(self):
return self.nome
class Beneficiente(models.Model):
ID = models.AutoField(primary_key=True)
nome = models.CharField(max_length=150)
CNPJ = models.IntegerField(max_length = 10)
def __str__(self):
return self.nome
class Favores(models.Model):
ID = models.AutoField(primary_key=True)
favor = models.CharField(max_length=150)
dataInserido = models.DateField()
usuarios = models.ForeignKey(Join)
def __str__(self):
return self.favor
class BeneficientePagar(models.Model):
ID = models.AutoField(primary_key=True)
moeda = models.IntegerField()
beneficiente = models.ForeignKey(Beneficiente)
join = models.ForeignKey(Join)
def __str__(self):
return self.ID
Thanks in advance
If using BeneficientPager, you need to do
BeneficientePagar.objects.filter(beneficient__nome__contains="Joao Pedro")
You are getting the error because nome is a field on Beneficiente, not BeneficientePagar.
You can either do
Beneficiente.objects.filter(nome__contains="Joao Pedro")
which will return a queryset of Beneficientes. Or if you need BeneficientePagar you can query through the foreign key.
BeneficientePagar.objects.filter(beneficiente__nome__contains="Joao Pedro")

Customizing drop down values with parent's model values in Django admin

I have few models in Django:
from django.db import models
class First(models.Model):
first_name = models.CharField('First Name', max_length=100)
first_value = models.IntegerField('Value')
def __unicode__(self):
return self.first_name
class Second(models.Model):
first_ref = models.ForeignKey(First)
second_name = models.CharField('Second Name', max_length=100)
second_value = models.IntegerField('Second Value')
def __unicode__(self):
return self.second_name
class Third(models.Model):
second_ref = models.ForeignKey(Second)
third_name = models.CharField('Third Name', max_length=100)
third_value = models.IntegerField('Third Value')
def __unicode__(self):
return self.third_name
Now, when I try to add a new record for Third model in my Django admin, my <select> box is populated with second_name values. How can I display a concatenated string of different values from both 'parent' tables, e.g. first_name + first_value + second_name + second_value?
Just update the unicode method of second Model:
class Second(models.Model):
first_ref = models.ForeignKey(First)
second_name = models.CharField('Second Name', max_length=100)
second_value = models.IntegerField('Second Value')
def __unicode__(self):
return '%s %s %s %s' % (
self.first_ref.first_name, self.first_ref.first_value,
self.second_name, self.second_value)