ForeignKey relation a better understanding
If there is someone here from the Django world that can teach the best practices regarding field lookups , and how they work . I tried they're documentation but i found it very confusing specially the relation between models and views regarding databases .
For example let's say we have the following structure : How should the view look and what is the best way to approach this kind of situations.
MODELS :
class Article(models.Model):
Author = models.CharField(max_length=255)
Title = models.CharField(max_length=255)
Content = models.TextField()
class comments(models.Model):
TheArticle = models.ForeignKey(Article)
c_Author = models.CharField(max_length=255)
c_Title = models.CharField(max_length=255)
c_Content = models.TextField()
View :
def page(request , URL_Title ): #comes trough the url setup
article = Article.objects.get( Title=URL_Title )
comments = # What is the Django way in getting the comments for the specified article ?
return render_to_response('base.html' , {'article':a开发者_JAVA技巧rticle , 'comments':comments } )
The Themplate :
{% if article %}
.....Print all the article related fields .....
{% if comments %}
{% for comment in comments %}
.....Print Comment .....
{% endfor %}
{% endif %}
{% endif %}
And if you have the time a example on a ManyToMany relation will also help .
Any help is highly appreciated .As noted in Following relationships "backward" it is possible to do so through Manager
that will be automatically available on Article
model instances. For manipulating related field see ForeingKey.related_name attribute.
article = Article.objects.get( Title=URL_Title )
comments = article.comments_set.all()
精彩评论