hai i have the following query
SELECT DISTINCT P.intPartID FROM tbmstpart p, tbtrnappraisalquestion q WHERE p.intPartID = q.intPartID AND q.intTemplateID =4
my models are
class tbmstpart(models.Model):
intPartID = models.AutoField(primary_key=True,db_column="intPartID")
vchPartname = models.CharField("PartName", max_length=50,db_column="vchPartname")
def __unicode__(self):
return self.vchPartname
class Meta:
db_table = 'tbmstpart'
verbose_name = 'PartName'
verbose_name_plural = 'PartNames'
class tbmstsection(models.Model):
intSectionID = models.AutoField(primary_key=True,db_column="intSectionID")
vchSectionName = models.CharField("SectionName", max_length=50,db_column="vchSectionName")
def __unicode__(self):
return self.vchSectionName
class Meta:
db_table = 'tbmstsection'
verbose_name = 'SectionName'
verbose_name_plural = 'SectionNames'
class tbtrnappraisalquestion(models.Model):
STATUS = (
('1','Yes'),
('0','No')
)
intQuesID = models.AutoField(primary_key=True,db_column="intQuesID")
intTemplateID= models.ForeignKey(tbmsttemplate,verbose_name="Template",db_column="intTemplateID",related_name="tbmsttemplate_intTemplateID")
intSectionID= models.ForeignKey(tbmstsection,verbose_name="Section",db_column="intSectionID",related_name="tbtrnappraisalquestion_intSectionID")
intPartID= models.ForeignKey(tbmstpart,verbose_name="Part",db_column="intPartID",related_name="tbtrnappraisalquestion_intPartID")
txtQuestion = models.TextField("Question",db_column="txtQuestion")
#txtQuestion = RichTextField()
enumRating = models.CharField("Rating",max_length=5,choices=STATUS,db_column="enumRating")
enumComment = models.CharField("Comment",max_length=5,choices=STATUS,db_column="enumComment")
intOrder = models.CharField("Sequence",max_length=2,db_column="intOrder")
def __unicode__(self):
return self.txtQuestion
class Meta:
db_table = 'tbtrnappraisalquestion'
verbose_name = 'AppraisalQuestion'
verbose_name_plural = 'AppraisalQuestions'
i tried in this way
parts_list = tbmstpart.objects.filter(tbtrnappraisalquestion__intTemplateID__exact=4)
but it is throwing an error
FieldError at /opas/list_questions_test/
Cannot resolve keyword 'tbtrnappraisalquestion' into field. Choices are: intPartID, tbtrnappraisalquestion_intPartID, vchPartname
thanks in advance?
You have typo of __ in tbtrnappraisalquestion__intTemplateID rather you want tbtrnappraisalquestion_intTemplateID, with single underscore.
Change your query to
Assuming your tbmsttemplate model has intTemplateID as int primary key,
parts_list = tbmstpart.objects.filter(tbtrnappraisalquestion_intPartID__intTemplateID__intTemplateID__exact=4)
#there is no typo here, you have to do __intTemplateID__intTemplateID as your pk field in `tbmsttemplate` and FK `tbtrnappraisalquestion` are same
i tried this one as said by #Rohan. its working fine
parts_list = tbmstpart.objects.filter(tbtrnappraisalquestion_intPartID__intTemplateID__exact=4).distinct()
Related
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')
)
I'm trying to make an API for an outside group where I define user access. I have a setup in django that makes it easy to administer, but I would like the output to be quite simplistic for the other team.
This is the output I'm looking for would be something like:
{
"user_list": {
"user": {
"username": "username1",
"top_accesses": ["top_access_1", "top_access_2", "top_access_5"],
"middle_accesses": ["middle_access_1", "middle_access_2", "middle_access_7"],
"lower_accesses": ["lower_access_1", "lower_access_2", "lower_access_22"],
},
"user": {
"username": "username2",
"top_accesses": ["top_access_1", "top_access_2", "top_access_8"],
"middle_accesses": ["middle_access_3", "middle_access_5", "middle_access_6"],
"lower_accesses": ["lower_access_21", "lower_access_33", "lower_access_36"],
}
}
}
However, I'm having trouble using django's built in ORM to come up with these sets from my models. I can think of how to do it in SQL, but this isn't a particularly clean method. I know there must be a better way to do it since using TabularInline shows exactly what I want to see in the admin page
Here are my models:
class TopAccess(models.Model):
name = models.CharField(max_length=100)
site_user_access = models.ManyToManyField(User, blank=True)
site_group_access = models.ManyToManyField(Group, blank=True)
class Meta:
verbose_name_plural = "Top Access"
def __str__(self):
return self.name
class MiddleAccess(models.Model):
name = models.CharField(max_length=100)
site_user_access = models.ManyToManyField(User, blank=True)
site_group_access = models.ManyToManyField(Group, blank=True)
class Meta:
verbose_name_plural = "Middle Access"
def __str__(self):
return self.name
class LowerAccess(models.Model):
name = models.CharField(max_length=100)
site_user_access = models.ManyToManyField(User, blank=True)
site_group_access = models.ManyToManyField(Group, blank=True)
class Meta:
verbose_name_plural = "Lower Access"
def __str__(self):
return self.name
Ideally I would be able to return a query object that plays well with the django-rest-framework in the end, since I like how nicely it returns the same data in whichever form is requested
Edit:
This is what I'm thinking is going to be close to the solution, but I know I'm using class inheritance incorrectly
class MaybeThisCouldWork(User):
t_user = TopAccess.objects.filter(site_user_access=User)
m_user = MiddleAccess.objects.filter(site_user_access=User)
l_user = LowerAccess.objects.filter(site_user_access=User)
user_groups = User.objects.filter(id=User)
for user_group in user_groups:
t_group = TopAccess.objects.filter(
site_group_access=user_groups
)
m_group = MiddleAccess.objects.filter(
site_group_access=user_groups
)
l_group = LowerAccess.objects.filter(
site_group_access=user_groups
)
t_user = t_user | t_group
m_user = m_user | m_group
l_user = l_user | l_group
You could use serializers, may be something like this,
class TopAccessSerializer(serializers.ModelSerializer):
class Meta:
model = TopAccess
fields = ['name']
class MiddleAccessSerializer(serializers.ModelSerializer):
class Meta:
model = MiddleAccess
fields = ['name']
class LowerAccessSerializer(serializers.ModelSerializer):
class Meta:
model = LowerAccess
fields = ['name']
class UserSerializer(serializers.ModelSerializer):
topaccess = TopAccessSerializer(source='topaccess_set', many=True)
middleaccess = MiddleAccessSerializer(source='middleaccess_set', many=True)
loweraccess = LowerAccessSerializer(source='loweraccess_set', many=True)
class Meta:
model = User
fields = ['username', 'topaccess', 'middleaccess', 'loweraccess']
class Entry(models.Model):
title = models.CharField(max_length=200)
post_type = models.CharField(max_length=50, default="others")
author = models.CharField(max_length=30, default = "")
body = models.TextField()
slug = models.SlugField(max_length = 200, unique = True)
publish = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now_add=True)
objects = EntryQuerySet.as_manager()
def __str__(self):
return self.title
class Meta:
verbose_name = "Blog Entry"
verbose_name_plural = "Blog Entries"
ordering = ["-created"]
The above code is my models.py
class MobilesIndex(generic.ListView):
queryset = models.Entry.objects.get(post_type="Mobile")
template_name = "index.html"
paginate_by = 5
def Mobiles(request):
context = locals()
template = "Mobiles.html"
return render(request,template,context)
The above code is view.py
how do i write the query that has only the posts that are of post_type="Mobile"
Try :
Entry.objects.fitler(post_type="Mobile")
get() return ONE object or exeception if not exists/multiple objects, but filter() returns all objects (or None if no objects).
queryset = models.Entry.objects.filter(post_type="Mobile")
this will give you all the post type and to render in template you need to loop it
I'm trying to customize and many to many inline in the django Admin, but I'm not able to display the fields of the underlying models.
Here's a simplified example. Maybe you can tell me how to reference them?
Here are my models:
class Clown(models.Model):
name = models.CharField(max_length=255)
def edit_link(self):
return ...
class Circus(models.Model):
clowns = models.ManyToManyField(Clown, blank=True, through='WorkedAt')
name = models.CharField(max_length=255)
class WorkedAt(models.Model):
clown = models.ForeignKey(Clown)
circus = models.ForeignKey(Circus)
and my admin:
class ClownInline(admin.TabularInline):
model = WorkedAt
fields = ['clown__name','clown__edit_link']
class CircusAdmin(admin.ModelAdmin):
inlines = [
ClownInline,
]
exclude = ('clowns',)
However I get this error:
Unknown field(s) (clown__name) specified for WorkedAt
(I'm on Django 1.6)
Update:
Why won't this work either. (Added calculated field to through model.)
class Clown(models.Model):
name = models.CharField(max_length=255)
def edit_link(self):
return ...
class Circus(models.Model):
clowns = models.ManyToManyField(Clown, blank=True, through='WorkedAt')
name = models.CharField(max_length=255)
class WorkedAt(models.Model):
clown = models.ForeignKey(Clown)
circus = models.ForeignKey(Circus)
#property
def edit_link(self):
return self.clown.edit_link()
and my admin:
class ClownInline(admin.TabularInline):
model = WorkedAt
fields = ['edit_link']
class CircusAdmin(admin.ModelAdmin):
inlines = [
ClownInline,
]
exclude = ('clowns',)
Try this. Hope it solves your problem
class ClownInline(admin.TabularInline):
model = WorkedAt
fields = ['clown_name', 'clown_edit_link']
readonly_fields = ['clown_name', 'clown_edit_link']
def clown_name(self, instance):
return instance.clown.name
clown_name.short_description = 'clow name'
def clown_edit_link(self, instance):
url = reverse("admin:%s_%s_change" % (instance.clown._meta.app_label, instance.clown._meta.module_name), args=(instance.clown.pk,))
return '%s' % (url, instance.clown.name)
clown_edit_link.allow_tags = True
class CircusAdmin(admin.ModelAdmin):
inlines = [
ClownInline,
]
exclude = ('clowns',)
I don't know if anyone still needs this, because this question is 4 years old but this solved my problem for in Django 2.0.3:
# models.py
class Clown(models.Model):
name = models.CharField(max_length=255)
def edit_link(self):
return ...
class Circus(models.Model):
clowns = models.ManyToManyField(Clown, blank=True, through='WorkedAt')
name = models.CharField(max_length=255)
class WorkedAt(models.Model):
clown = models.ForeignKey(Clown)
circus = models.ForeignKey(Circus)
# admin.py
class WorkedAtInline(admin.TabularInline):
model = WorkedAt
extra = 1
class WorkedAtAdmin(admin.ModelAdmin):
inlines = (WorkedAtInline,)
admin.site.register(Clown, WorkedAtAdmin)
Hope this helps anyone that stumbles upon this problem and looks into this answer.
i have the following models
class SchoolClass(models.Model):
id = models.AutoField(primary_key = True)
class_name = models.TextField()
level = models.IntegerField()
taught_by = models.ManyToManyField(User,related_name="teacher_teaching",through='TeachSubject')
attended_by = models.ManyToManyField(User,related_name='student_attending')
def __unicode__(self):
return self.class_name
class Meta:
db_table = 'classes'
class Relationship(models.Model):
rChoices = (
(1,'Mother'),
(2,'Father'),
(3,'Guardian'),
)
parent = models.ForeignKey(User,related_name='parent')
student = models.ForeignKey(User,related_name='child')
relationship = models.IntegerField(choices= rChoices)
#add in __unicode__ for admin name
class Meta:
unique_together = ('parent','student')
db_table = 'relationship
I have the the pk of the class, and I want to find out who are the parents of the students in the selected class.
My feeble attempt is:
selected_class = SchoolClass.objects.get(pk=class_id)
studs = selected_class.attended_by.all().select_related()
r = Relationship.objects.filter(student__in=students)
parents = [.parent for p in r]
Now, I am just curious if there is a shorter or more efficient way of doing this(i'm sure missed something in the docs) ?
This should work
parents = Relationship.objects.filter(student__schoolclass__id=class_id).values_list('parent', flat=True)
"To refer to a "reverse" relationship, just use the lowercase name of the model". (docs)