How to access model with only two foreign keys?
This should be really simple, I could do it without thinking on traditional SQL but can't get it with Django models!
I have a model with two foreign keys to create many to many relationship - I am not using many to many field in Django
class Story(models.Model):
title = models.CharField(max_length=200)
pub_date = models.DateTimeFi开发者_如何学Celd('date published')
def __unicode__(self):
return self.title
class Category(models.Model):
categoryText = models.CharField(max_length=50)
parentCat = models.ForeignKey('self',null=True,blank=True)
def __unicode__(self):
return self.categoryText
class StoryCat(models.Model):
story = models.ForeignKey(Poll,null=True,blank=True)
category = models.ForeignKey(Category,null=True,blank=True)
def __unicode__(self):
return self.story
I would like to query for a category like 'short', and retrieve all the unique keys to all stories returned.
c=Category.objects.get(categoryText='short')
s=StoryCat.objects.get(category=c)
when I try this I get an error that multiple rows were returned. I actually want to just retrieve the id values but I don't seem to be able to figure how to do this.
How can I get the id values that are returned?
"multiple rows were returned" is because you are using get rather then filter on either or both of the queries.
If there is only one category matching short try:
c = Category.objects.get(categoryText='short')
s = StoryCat.objects.filter(category=c)
If it is possible for there to be more then one category try something like the following:
# get just ids via values_list
cids = Category.objects.filter(categoryText='short').values_list('id', flat=True)
s = StoryCat.objects.filter(category__id__in=cids)
精彩评论