开发者

Model with Foreign keys not behaving as expected - Django

开发者 https://www.devze.com 2023-03-19 21:13 出处:网络
I have a model with two foreign keys to create many to many relationship - I am not using many to many field in Django

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.DateTimeField('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(categoryText='short')
>开发者_开发问答>>s=StoryCat(category=c)

when I try this I get errors "AttributeError: 'NoneType' object has no attribute 'title'. How can I do this?


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')
story_ids = StoryCat.objects.filter(category=c).values_list('story')

And about your models:

Category name should probably be unique. And declare your many-to-many relation.

class Category(models.Model):
   categoryText = models.CharField(max_length=50, unique=True)
   stories = models.ManyToManyField(Story, through='StoryCat')
   ...

It makes no sense for intermediary table FK fields to be nullable. Also I assume the same story should not be added to the same category twice, so set a unique constraint.

class StoryCat(models.Model):
    story = models.ForeignKey(Poll)
    category = models.ForeignKey(Category)

    class Meta:
        unique_together = ('story', 'category') 


The lines you're executing in the interpreter are not queries - they are instantiating new objects (but not saving them).

Presumably you meant this:

>>>c=Category.objects.get(categoryText='short')
>>>s=StoryCat.objects.get(category=c)
0

精彩评论

暂无评论...
验证码 换一张
取 消