Re: help with foreignkeys
When you have a FK to park in your comment model, you automatically get a reference to a list of comments from the park model. E.g:
class Park(models.Model):
#Park fields here, but no explicit relationship to Comment
class Comment(models.Model):
park = models.ForeignKey(Park)
#other comment fields here
def some_view(request, id):
park = Park.objects.get(pk=id)
comments = park.comment_set #this is a queryset of all comments associated with the part; it may be empty
#etc...
Or in a template:
{% for comment in park.comment_set.all %}
{{ comment.body }}
{% endfor %}
Does that make sense? Here are the official docs for this functionality: https://docs.djangoproject.com/en/dev/topics/db/queries/#related-objects
_Nik
On May 13, 2012, at 7:03 PM, psychok7 wrote:
i think you are right :) , i can always get the parks associated comments if i query comments model (im used to only doing it the other way around). gonna try that outthanks
On Monday, May 14, 2012 2:57:17 AM UTC+1, jondykeman wrote:If all comment have to have a park and user.I would have a ForeignKey to Park and User in the Comments model, and no Foreign key in the Parks model.As such a comment will always need to be linked to an existing park and user object, but a park can be created without needing a comment.JD
On Sunday, May 13, 2012 7:53:58 PM UTC-6, psychok7 wrote:yes, like a park doesn't have to have comments, but all the comments must have an associated park and user all the time.what is the django syntax for me to achieve this?
On Monday, May 14, 2012 2:49:18 AM UTC+1, jondykeman wrote:As far as I understand it the ForeignKey will have to be unique=True and null=False.I want to get a better sense of what you are trying to achieve. Is it that you want to link comment and park only some of the time?JD
On Sunday, May 13, 2012 7:41:39 PM UTC-6, psychok7 wrote:so i have this 2 models (Comment and Park)Comment has a foreign key to USER and PARKPARK has a foreign key to Commentmy question is, isn't there going to be a deadlock if i don't have a comment or a park created? i mean , in order to create a Park i need to have a comment, and in order to create a comment i need a park and a user.is there a way for me to fix my problem? like allowing the foreign key to be null or something like that?thanks in advance--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/EyGby9pYGwMJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home