I have the following two models:
class StraightredFixture(models.Model):
fixtureid = models.IntegerField(primary_key=True)
home_team = models.ForeignKey('straightred.StraightredTeam', db_column='hometeamid', related_name='home_fixtures')
away_team = models.ForeignKey('straightred.StraightredTeam', db_column='awayteamid', related_name='away_fixtures')
fixturedate = models.DateTimeField(null=True)
fixturematchday = models.ForeignKey('straightred.StraightredFixtureMatchday', db_column='fixturematchday')
hometeamscore = models.IntegerField(null=True)
awayteamscore = models.IntegerField(null=True)
soccerseason = models.ForeignKey('straightred.StraightredSeason', db_column='soccerseasonid', related_name='fixture_season')
def __unicode__(self):
return self.fixtureid
class Meta:
managed = True
db_table = 'straightred_fixture'
class UserSelection(models.Model):
userselectionid = models.AutoField(primary_key=True)
campaignno = models.CharField(max_length=36,unique=False)
user = models.ForeignKey(User, related_name='selectionUser')
teamselection1or2 = models.PositiveSmallIntegerField()
teamselectionid = models.ForeignKey('straightred.StraightredTeam', db_column='teamselectionid', related_name='teamID')
fixtureid = models.ForeignKey('straightred.StraightredFixture', db_column='fixtureid')
class Meta:
managed = True
db_table = 'straightred_userselection'
I am using the following query:
prevWeekTeams = UserSelection.objects.select_related().filter(soccerseason=1025,fixturematchday=5,user=currentUserID).order_by('teamselection1or2')
When it is run I get the following error:
Cannot resolve keyword 'soccerseason' into field. Choices are: campaignno, fixtureid, fixtureid_id, teamselection1or2, teamselectionid, teamselectionid_id, user, user_id, userselectionid
I knew it would not work but I can't quite understand how to refer to the soccerseason within the fixture table. Any help would be appreciated. Many thanks, Alan.
PS
If you require the other two models that are linked to just let me know.
You just need to filter on field of foreign model with that format
field-that-reference-to-foreign-model__foreign-model-field in your case fixtureid__soccerseason. The docs where it describes at best.
What you should do is
prevWeekTeams = UserSelection.objects.filter(fixtureid__soccerseason=1025,fixtureid__fixturematchday=5,user=currentUserID).order_by('teamselection1or2')
Related
I want to access verbose name of models to put it as a key in serializer. But I can't find a way to do it.
My models are:
class ProductCategory(models.Model):
name = models.CharField(max_length=150, unique=True)
created_at = models.DateTimeField(default=timezone.now)
modified_at = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.name
class DeviceTypeCategory(ProductCategory):
product_category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE,
related_name="device_types")
class Meta:
verbose_name = _("Device type")
verbose_name_plural = _("Device types")
class DeviceBrandCategory(ProductCategory):
product_category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE,
related_name="device_brands")
class PartTypeCategory(ProductCategory):
product_category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE, related_name="part_types")
And my serializer:
class ProductCategorySerializer(serializers.ModelSerializer):
device_types = serializers.StringRelatedField(many=True)
device_brands = serializers.StringRelatedField(many=True)
part_types = serializers.StringRelatedField(many=True)
class Meta:
model = ProductCategory
fields = ('name', 'device_types', 'device_brands', 'part_types')
Any suggestions would help. I would also be glad to hear out other ideas on how to create categories model. I've tried django-mptt, but I need product to belong to multiple subcategories. The django-polymorphic-mptt could have help. But I couldn't find proper documentation.
You can do something like the following:
class ProductCategorySerializer(serializers.ModelSerializer):
device_types = serializers.StringRelatedField(many=True)
device_brands = serializers.StringRelatedField(many=True)
part_types = serializers.StringRelatedField(many=True)
plural_name = serializers.SerializerMethodField()
def get_plural_name(self, obj):
return ProductCategory._meta.verbose_name_plural
class Meta:
model = ProductCategory
fields = ('name', 'device_types', 'device_brands', 'part_types', 'plural_name')
Currently experiencing a problem where my models aren't joining on the foreign key properly,
Doctors can only have one toolset, essentially I need to return [DoctorName, Category, Type, Subtype, Syringe, Bandage]
ToolSetCategoryID, ToolSetTypeID, ToolSetSubTypeID all join on each other's respective tables and all join back to ToolSets
an example of the models would be:
class Doctor(models.Model):
DoctorID = models.AutoField(db_column='DoctorID', primary_key=True)
ToolSetID = models.ForeignKey("ToolSets", db_column='ToolSetID', on_delete=models.CASCADE)
DoctorName = models.CharField(db_column='DoctorName', max_length=100)
class Meta:
managed = False
db_table = 'tblDoctors'
default_permissions = ['add','edit','delete']
class ToolSetCategories(models.Model):
ToolSetCategoryID = models.AutoField(db_column='ToolSetCategoryID', primary_key=True)
Category = models.CharField(db_column='Category', max_length=100)
class Meta:
managed = False
db_table = 'tblToolSetCategories'
default_permissions = ['add','edit','delete']
class ToolSetTypes(models.Model):
ToolSetTypeID = models.AutoField(db_column='ToolSetTypeID', primary_key=True)
ToolSetCategoryID = models.ForeignKey("ToolSetCategories",db_column='ToolSetCategoryID',on_delete=models.CASCADE)
Type = models.CharField(db_column='Type', max_length=100)
class Meta:
managed = False
db_table = 'tblToolSetTypes'
default_permissions = ['add','edit','delete']
class ToolSetSubTypes(models.Model):
ToolSetSubTypeID = models.AutoField(db_column='ToolSetSubTypeID', primary_key=True)
ToolSetTypeID = models.ForeignKey("ToolSetTypes",db_column='ToolSetTypeID',on_delete=models.CASCADE)
ToolSetCategoryID = models.ForeignKey("ToolSetCategories",db_column='ToolSetCategoryID',on_delete=models.CASCADE)
SubType = models.CharField(db_column='SubType', max_length=100)
class Meta:
managed = False
db_table = 'tblToolSetSubTypes'
default_permissions = ['add','edit','delete']
class ToolSets(models.Model):
ToolSetID = models.AutoField(db_column='ToolSetID', primary_key=True)
ToolSetCategoryID = models.ForeignKey("ToolSetCategories",db_column='ToolSetCategoryID',on_delete=models.CASCADE)
ToolSetTypeID = models.ForeignKey("ToolSetTypes",db_column='ToolSetTypeID',on_delete=models.CASCADE)
ToolSetSubTypeID = models.ForeignKey("ToolSetSubTypes",db_column='ToolSetSubTypeID',on_delete=models.CASCADE)
Syringe = models.CharField(db_column='Syringe', max_length=100)
Bandage = models.CharField(db_column='Bandage', max_length=100)
class Meta:
managed = False
db_table = 'tblToolSets'
default_permissions = ['add','edit','delete']
I've found either the fix or a workaround.
I had to filter the conditions I would've used in a join instead of using a join.
You can use Django's built in function F in order to reference a fields dynamic data to filter against (such as filtering field data against another field's data).
Not the best looking solution but is working for now, if anyone can find a more efficient way of doing this please post an answer below.
from django.db.models import F
Doctor.objects.using("test").filter(DoctorID=DoctorID).filter(
ToolSetID__ToolSetTypeID__ToolSetCategoryID=F("ToolSetID__ToolSetCategoryID"),
ToolSetID__ToolSetSubTypeID__ToolSetTypeID=F("ToolSetID__ToolSetTypeID"),
ToolSetID__ToolSetSubTypeID__ToolSetCategoryID=F("ToolSetID__ToolSetCategoryID"),
)
I connected my database to django. I want to enable user (teacher) insert the name of a student and get test results on certain subjects.
I run python3 manage.py inspectdb and inserted it into models.py
class Profilez(models.Model):
student = models.CharField(max_length=255)
schgroup = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'profilez'
class Schoolz(models.Model):
profilez_id = models.AutoField(primary_key=True)
lit = models.IntegerField(blank=True, null=True)
math = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'schoolz'
in forms.py i put:
class StudentForm(forms.ModelForm):
SUB = (
('lit', 'lit'),
('math', 'math')
)
student = forms.CharField(max_length=150, label='', widget=forms.TextInput)
class Meta:
model = Schoolz
fields = ('student',)
in views.py:
def home(request):
if request.method == "POST":
form = StudentForm(request.POST)
if form.is_valid():
form1 = form.save(commit=True)
name = form1.student
ab=schoolz.objects.all()
context={
'name':name,
}
return render(request, 'book/analysis.html', context)
else:
form = StudentForm()
return render(request, 'book/search.html', {'form': form})
Can you please help me to understand what i am doing wrong and how to get value for certain subject for exmaple math subject.
I would appreciate help and guidance to undertand and execute it. I am struggling a month.
Notes
Add a field in Profile that should be unique for each student. Currently I am assuming name and surname combination will be unique.
If you use ajax, you can get score without refresh. Current way I have used is not very good.
You don't have to write models if you already have in DB. You can remove your models. add already present models in models.py and makemigrations and migrate.
Add a ForiegnKey field in Class10
class Class10(models.Model):
profile_id = models.IntegerField()
math = models.IntegerField()
literature = models.IntegerField()
biology = models.IntegerField()
student = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='stud_name') # add this in model
class Meta:
managed = False # make this True otherwise makemigrations won't get the changes.
db_table = 'class_10'
class Profile(models.Model):
student_name = models.CharField(max_length=255)
student_surname = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'profile'
views.py
def home(request):
if request.method == "POST":
form = StudentlForm(request.POST)
if form.is_valid():
form_1 = form.save(commit=False)
name = form_1.student_name
surname = form_1.student_surname
subject = form_1.subject
fil = Q(student__student_name=name) & Q(student__student_surname=surname)
student_1 = StudentScore.objects.filter(fil).values()
score = student_1[0][subject] # answer
context={
'score':score
}
return render(request, 'school/analysis.html', context)
else:
form = StudentlForm()
return render(request, 'school/search.html', {'form': form})
forms.py
class StudentForm(forms.ModelForm):
SUB = (
('math', 'math'),
('literature', 'literature'),
('biology', 'biology')
)
student_name = forms.CharField(max_length=150, label='', widget=forms.TextInput)
student_surname = forms.CharField(max_length=150, label='', widget=forms.TextInput)
subject = forms.CharField(widget=forms.Select(choices=SUB))
class Meta:
model = Profile
fields = ('student_name', 'student_surname', 'subject')
#Nina,
Please look on the relationship> it's general idea for the Student & Gradesheet model
class Student(models.Model):
std_name = models.CharField(max_length=100)
def __str__(self):
return self.std_name
class Gradesheet(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE)
sub = models.CharField(max_length=50)
grade = models.CharField(max_length=50)
def __str__(self):
return self.student.std_name
So if you need to search for a student grade for particular subject:
std_info = Student.objects.get(std_name='Nina')
Then you will get a Student Class instance for Nina.
Now fetch the data by relationship:
std_grade = std_info.gradesheet_set.filter(sub='math')
You will get QuerySet. Then just :
std_grade[0].grade
You will get your student's grade for particular subject. Look its a model relationship. So you may use other filtering options also to get your desired result.
According to your given model:
Instead of the profile_id you should use the Profile object which will help you to take the control through django ORM.
class Profile(models.Model):
student_name = models.CharField(max_length=255)
student_surname = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'profile'
class Class10(models.Model):
#profile_id = models.IntegerField()
profile = models.OneToOneField(Profile, on_delete=models.CASCADE,related_name='profile')
math = models.IntegerField()
literature = models.IntegerField()
biology = models.IntegerField()
class Meta:
managed = False
db_table = 'class_10'
So your query can be build by:
std_profile = Profile.objects.get(student_name='SomeoneName')
Now turn it for get the grade. Result would be:
math_grade = std_profile.profile.math
biology_grade = std_profile.profile.biology
literature_grade = std_profile.profile.literature
average_grade = ((math_grade + biology_grade + literature_grade)/3)
Here, your model relationship:Profile to Class10 is OneToOne
I have this model in models.py:
class Foo(models.Model):
bar = models.ManyToManyField('self')
How can I serialize it?
I was using one of solutions from this topic: Django rest framework nested self-referential objects But none of them working with M2M, either causes in infinity cycle of serialization. Solution where I'm using a row of serializers works good except it's limited by copy&paste (sounds really sad :) )
Generic model mostly looks like a comment's tree. I hope such a problem was already solved before but haven't found how yet.
I don't think you will get a straight solution to this, so try this
class FooBaseSerializer(serializers.ModelSerializer):
class Meta:
fields = '__all__'
model = Foo
class FooSerializer(FooBaseSerializer):
bar = FooBaseSerializer(many=True)
NOTE: As a Software Engineer, I love to use Architectures and I have deeply worked on Layered Approach for Development so I am gonna be Answering it with Respect to Tiers.
I would suggest the use of a Bridge Table for M2M relationships to Normalize Stuff. Anyhow serializing many of the Items would require to
serializer = SerializerNameGoesHere(AllFilteredObjectsfromModel, many=True)
would serializer m2m.
Here's an Example in Layered Approach!
As i understood the Issue, Here's the Solution
models.py
class Member(models.Model):
member_id = models.AutoField(primary_key=True)
member_name = models.CharField(max_length =
class Group(models.Model):
group_id = models.AutoField(primary_key=True)
group_name = models.CharField(max_length = 20)
fk_member_id = models.ForeignKey('Member', models.DO_NOTHING,
db_column='fk_member_id', blank=True, null=True)
class Membership(models.Model):
membershipid = models.AutoField(primary_key=True)
fk_group_id = models.ForeignKey('Group', models.DO_NOTHING,
db_column='fk_member_id', blank=True, null=True)
join_date = models.DateTimeField()
serializers.py
import serializer
class AllSerializer(serializer.Serializer):
group_id = serializer.IntegerField()
group_name = serializer.CharField(max_length = 20)
join_date = serializer.DateTimeField()
CustomModels.py
imports...
class AllDataModel():
group_id = ""
group_name = ""
join_date = ""
BusinessLogic.py
imports ....
class getdata(memberid):
alldataDict = {}
dto = []
Member = models.Members.objects.get(member_id=memberid) #or use filter for Name
alldataDict["MemberId"] = Member.member_id
alldataDict["MemberName"] = Member.member_name
Groups = models.Group.objects.filter(fk_member_id=Member)
for item in Groups:
Custommodel = CustomModels.AllDataModel()
Custommodel.group_id = item.group_id
Custommodel.group_name = item.group_name
Membership = models.Membership.objects.get(fk_group_id=item.group_id)
Custommodel.join_date = Membership.join_date
dto.append(Custommodel)
serializer = AllSerializer(dto,many=True)
alldataDict.update(serializer.data)
return alldataDict
Im new to django. I have this model, In tblperson, only the forgein keys of type and status are saved. How do I join all tables to display their value not their forgein key? For example.
TblPerson.objects.raw('SELECT * FROM "Tblperson" INNER JOIN "Tblstatus" ON ("TblPerson"."Status" = "Tblstatus"."ID")'):
Thanks.
class TblPerson(models.Model):
ID = models.AutoField(primary_key=True, db_column=u'ID')
Type = models.IntegerField(null=True, db_column=u'Type', blank=True)
Status = models.IntegerField(null=True, db_column=u'Status', blank=True)
class Meta:
db_table = u'tblPerson'
class Tblstatus(models.Model):
ID = models.AutoField(primary_key=True, db_column=u'statStatusID')
Status = models.CharField(max_length=25, db_column=u'statStatus', blank=True)
class Meta:
db_table = u'tblStatus'
class Tbltype(models.Model):
ID = models.AutoField(primary_key=True, db_column=u'typTypeID')
Type = models.CharField(max_length=25, db_column=u'typType', blank=True)
class Meta:
db_table = u'tblType'
The power of Django is in the ORM, which means you should be writing very little SQL if at all.
class Person(models.Model):
#don't use this because id is generated automatically
#ID = models.AutoField(primary_key=True, db_column=u'ID')
type = models.ForeignKey(Type)
status = models.ForeignKey(Status)
#Type,Status analogous
#filter like this
selected = Person.objects.filter(type=SomeType)
for p in selected:
print p.id,p.type,p.status
I would suggest you to re-write your models. So, that your TblPerson has a many to one relationship with Tblstatus
class TblPerson(models.Model):
ID = models.AutoField(primary_key=True, db_column=u'ID')
Type = models.IntegerField(null=True, db_column=u'Type', blank=True)
Status = models.ForeignKey(Tblstatus, null=True, db_column=u'Status', blank=True)
class Meta:
db_table = u'tblPerson'
class Tblstatus(models.Model):
ID = models.AutoField(primary_key=True, db_column=u'statStatusID')
Status = models.CharField(max_length=25, db_column=u'statStatus', blank=True)
class Meta:
db_table = u'tblStatus'
Using this you would be able to query for TblPerson objects for which Tblstatus exists like this
TblPerson.objects.filter(Status__isnull=False)