【问题标题】:Model with Foreign keys not behaving as expected - Django具有外键的模型未按预期运行 - Django
【发布时间】:2011-07-12 10:49:21
【问题描述】:

我有一个带有两个外键的模型来创建多对多关系 - 我没有在 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

我想查询像“短”这样的类别,并检索返回的所有故事的所有唯一键。

>>>c=Category(categoryText='short')
>>>s=StoryCat(category=c)

当我尝试这个时,我得到错误“AttributeError:'NoneType'对象没有属性'title'。我该怎么做?

【问题讨论】:

  • 我很想知道为什么你在StoryCat 上的字段是null=True, blank=True
  • 主要是因为我是 Django 新手 - 我会在学习时修复它们 - 现在是学习时刻之一 - 谢谢

标签: django django-models


【解决方案1】:

我想查询像“短”这样的类别,并检索返回的所有故事的所有唯一键。

c=Category.objects.get(categoryText='short')
story_ids = StoryCat.objects.filter(category=c).values_list('story')

关于你的模型:

类别名称应该是唯一的。并声明您的多对多关系。

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

中间表 FK 字段可以为空是没有意义的。另外我假设同一个故事不应该被两次添加到同一个类别中,所以设置一个唯一的约束。

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

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

【讨论】:

    【解决方案2】:

    您在解释器中执行的行不是查询 - 它们正在实例化新对象(但不保存它们)。

    大概你的意思是这样的:

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

    【讨论】:

    • 这接近我想要完成的 - 当我执行上述操作时,我收到有关返回多行的错误。我需要做的只是获取查询返回的 id 值。
    猜你喜欢
    • 2014-09-21
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    相关资源
    最近更新 更多