Retrieving data from multiple tables

19 views
Skip to first unread message

Suraj Thapa FC

unread,
Aug 21, 2019, 5:16:12 AM8/21/19
to django...@googlegroups.com
This is my model

class courses(models.Model):
cid = models.UUIDField(default=uuid.uuid4, editable=True, primary_key=True)
course_title = models.CharField(max_length=255, default="")


class course_rating(models.Model):
cr_id = models.BigAutoField(primary_key=True)
cid = models.ForeignKey(courses,on_delete=models.CASCADE)
userid = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
rating = models.IntegerField(validators[MaxValueValidator(5),MinValueValidator(1)],default=1)




I want to fetch the course_title and cid from courses tables and want to perform the average rating of courses 
Can someone write the query set for the same

Sundararajan Seshadri

unread,
Aug 21, 2019, 8:53:51 AM8/21/19
to Django users
What you need to appreciate is that the foreign key field gives you the full record (corresponding to the foreign key).

So, if you fetch all records as course_rating.objects.all() then c.cid will also be an object giving you the corresponding foreign key record. So, you can access c.cid.cid and c.cid.course_title.(where c is one instance / record of the query set)

Some points:
(a) you are not following the convention. Not a crime. But if you follow the convention, it will prove convenient. For example. Courses will be the class name. (Table name can be anything)
(b) You named the foreign-key in the second table as cid, It is, again, not an issue but if you followed the convention, you could have called it as course so that field names could have been c.course.cid and c.course.course_title, probably more meaningful.

Again, convention is for convenience. 

Cheers.
====================================

Suraj Thapa FC

unread,
Aug 21, 2019, 10:57:24 AM8/21/19
to django...@googlegroups.com
Thanks... 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f49660db-c157-43df-8563-3e9c2369a8dd%40googlegroups.com.

Amitesh Sahay

unread,
Aug 21, 2019, 1:21:50 PM8/21/19
to django...@googlegroups.com
I am not much of a database guy. But if you wish to get something from different table, then there has to be some foreignkey there I guess your "courses" table should have CID as foreignkey. May be I am wrong. 


Suraj Thapa FC

unread,
Aug 22, 2019, 1:19:30 AM8/22/19
to django...@googlegroups.com
Yes it has
.... 
Can you write the query for the above question asked

Reply all
Reply to author
Forward
0 new messages