How to access foreign key table's data in Django templates? - python

I want to access foreign key table's data into django templates.
my code is as below.
class TutorialCategory(models.Model):
tutorial_category = models.CharField(max_length=200)
category_summary = models.CharField(max_length=200)
category_slug = models.CharField(max_length=200, default=1)
class TutorialSeries(models.Model):
tutorial_series = models.CharField(max_length=200)
tutorial_category = models.ForeignKey(TutorialCategory, verbose_name="Category", on_delete=models.SET_DEFAULT)
series_summary = models.CharField(max_length=200)
Tutorial_obj = TutorialSeries.objects.get(pk=1)
{{ Tutorial_obj.tutorial_series}}
{{Tutorial_obj.category_summary}} // Not able to access TutorialCategory
I have searched on SO also & found to use _set which I have used but still not able to access table.
Pls if anyone have suggestion pls guide me .

You want
{{Tutorial_obj.tutorial_category.category_summary}}
Not sure if that was just a silly error or a misunderstanding of how it's supposed to work
BTW stick to the conventions: an instance really should be lower case tutorial or tutorial_obj if you insist.

Related

How can I construct a Django model whose fields are dependent upon another model's fields

I currently am making a simple newspaper Django application, and am working on the Articles model which looks as follows:
class Article(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
#date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
)
topic = models.CharField(max_length=255)
score_choices = [(-5,'-5'), (-4, '-4'), (-3,'-3'), (-2, '-2'), (-1,'-1'),
(0,'0'),(1,'1'), (2,'2'), (3,'3'), (4,'4'), (5,'5')]
score = models.IntegerField(choices=score_choices, default=0)
I am attempting to create another model that looks something like this:
class Topic(models.Model):
topic_name = models.CharField(max_length=255)
average_score =
Within the topic model, what I would like to do is somehow query all the Articles that have topic_name as their topic, and then return a list of scores that have been entered for Articles with that topic.
I'm currently pretty lost on this issue and I'm not even sure anymore if using the Django models is the best route. I've been reading through the Django Documentation as well as Third-Party books for a while but I can't find any reference here.
To summarize, I have two models: Article and Topic. Article has a field called 'topic' as well and I would like to create a field for my Topic class that is a function of the score field for all Article objects whose 'topic' field agrees with that of my separate Topic class. I apologize if this is confusing and I don't know all the terminology as I am trying to teach myself.
I have read through Django Documentation's pages on Models, Queries, Many-to-Many Relationships and various other properties. I still am unsure as to the solution.
Something like the following would work, using aggregation:
from django.db.models.aggregates import Avg
class Topic(models.Model):
topic_name = models.CharField(max_length=255)
def average_score(self):
return Article.objects.filter(topic=self.topic_name).aggregate(avg=Avg('score')).get('avg')

Using tastypie to retrieve data from foreign key

These are two models in my Django app :
models.py
class Posts(models.Model):
title = models.CharField(max_length=200, blank=True)
author = models.ForeignKey(user,on_delete=models.CASCADE,default=None, blank=True)
content = models.TextField()
class Unposted(models.Model):
article = models.ForeignKey(Posts, on_delete=models.CASCADE)
upload_at = models.DateTimeField(default=datetime.now, blank=True)
I'm trying to retrieve data from Posts using an API request to Unposted.
Here's what I have until now but I'm unsure how to get data from the Posts model. Right now I just get a JSON response with only the upload_at field.
resources.py
class UnpostedResource(ModelResource):
class Meta:
queryset = Unposted.objects.all()
resource_name = 'unposted'
If I'm not wrong, u can just import your Posts model and then just by for loop make an array with posts models using foreign key from unposted to filter your posts =) Sounds weird and I'm not sure about effectiveness, but looks pretty nice. It will look smth like:
queryset = Posts.objects.filter(article_in=[get(i.article) for i in Unposted.objects.all()])
In the case, Posts is a foreignkey of Unposted, thus you need to define foreignkey field in the resource for the corresponding field in model, this tutorial maybe can help you.

Django count foreign key through relation

I am building a simple forum application and I need some help with counting foreign key objects via through relation.
Let's say my models look like this:
class Forum(models.Model):
title = models.CharField(max_length=255)
description = models.TextField()
slug = models.SlugField(unique=True, blank=True)
class Thread(models.Model):
title = models.CharField(max_length=255)
forum = models.ForeignKey(to=Forum, related_name='threads')
slug = models.SlugField(unique=True, blank=True)
class Post(models.Model):
body = models.TextField()
author = models.ForeignKey(User)
thread = models.ForeignKey(to=Thread,related_name='posts')
Now we create forum object.
forum = Forum.objects.get(slug=forum)
We can count the number of threads inside forum like this: forum.threads.count()
My question is, how can i count all the posts in a forum?
I've tried something like all_posts = forum.thredas.posts.count() but as expected it didn't work.
Thanks!
Generally in Django it is a good principle that when you want to do something with a model, you should start your query from that model. So, since you need to count posts, you should start with the Post model.
From there you can use the double-underscore syntax to filter to the particular Forum you want.
forum_posts = Post.objects.filter(thread__forum=my_forum)
forum_post_count = forum_posts.count()

Django import problem with models.py and multiple ManyToManyFields()

I am working on creating a simple contest submission system using django. This is my first real django project. Basically each user can view a list of problems, submit a file, and view a results page.
Each problem can be associated with multiple contests, and different contests can use the same problem. Because of this, both problem and contest have a manyToManyField with each other. This is what is causing my problem.
Here is the initial models.py implementation I am going with:
startfile
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50)
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
class Problem(models.Model):
name = models.CharField(max_length=50)
filename = models.CharField(max_length=300)
contests = models.ManyToManyField(Contest)
class Contest(models.Model):
name = models.CharField(max_length=50)
problems = models.ManyToManyField(Problem)
date = models.DateField()
class Submission(models.Model):
user = models.ForeignKey(User)
problem = models.ForeignKey(Problem)
filename = models.CharField(max_length=300)
endfile
Is there a simple way to fix this? Or should I rethink my entire layout? I tried breaking each class into its own django app but I don't think thats how I should do it. The error I get is that Contest can not be found (because it exists lower in the file).
All advice is appreciated!
You don't need a ManyToManyField in both Contest and Problem. Many-to-many fields are already bidirectional. Just put it on one - doesn't matter which.
Djano will automatically create the reverse relation for you, so you only need to create it one end, eg.
class Problem(models.Model):
name = models.CharField(max_length=50)
filename = models.CharField(max_length=300)
contests = models.ManyToManyField(Contest, related_name='problems')
related_name gives you the possibility to assign a name to the reverse relation. Without defining the relation on the Contest model, you can then access eg. a_contest.problems.all()!

Django One-To-Many Models

The following models describe a vulnerability and the URLs out on the internet that reference that vulnerability. Assume that each URL only ever talks about 1 vulnerability, and that many URLs will discuss that vulnerability. Is this the correct way to lay out the model?
class Vuln(models.Model):
pub_date = models.DateTimeField("Publication Date")
short_description = models.CharField("Description", max_length=70)
reference_urls = models.ForeignKey(Url, unique=True, blank=True, verbose_name="Reference URLs")
vendor = models.ForeignKey(Vendor, verbose_name="Vendor")
class Url(models.Model):
url = models.URLField("URL", max_length=200)
The Admin application gives a 'select' box for the reference URLs, which isn't what I want. When I add a new vulnerability object, all of the existing URLs that have been entered show up in that dropdown, which is again unnatural. I feel like this should behave very similar to how a blog comment would, ie. the comment applies to a single blog entry and none other and that one blog entry may have many comments. How do I express this in a Django model?
It should be more like this:
class Vuln(models.Model):
pub_date = models.DateTimeField("Publication Date")
short_description = models.CharField("Description", max_length=70)
vendor = models.ForeignKey(Vendor, verbose_name="Vendor")
class Url(models.Model):
url = models.URLField("URL", max_length=200)
vulnerability = models.ForeignKey(Vuln)
If you're saying each Url talks about a specific vulnerability, then there is your relation in the Django DBM :)
As for the vendor field, you simply add another class, much like Class Vuln. For example:
class Vendor(models.Model):
field_names_go_here = models.TextField(max_length=70)
short_description = models.CharField("Description", max_length=70)
Hope this helps!
Regards, Alex

Categories

Resources