【问题标题】:Django relationships to inherited model from parent modelDjango 与从父模型继承的模型的关系
【发布时间】:2019-12-12 14:02:14
【问题描述】:

我在 django 中有 4 个模型,这里有 3 个(第 4 个是默认用户模型):

class Post(models.Model):
    title = CharField(max_length=200)
    content = TextField()

    def __str__(self):
        return self.title


class NewsArticle(Post):
    link = URLField(default='')
    external_id = CharField(unique=True,
                            max_length=50, help_text='The ID of the news article from the source')
    source = CharField(max_length=15, help_text='Name of source website')

class Like(models.Model):
    LIKE_CHOICES = [('L', 'Like'), ('D', 'Dislike')]

    user = ForeignKey(User, on_delete=models.CASCADE)
    post = ForeignKey(Post, on_delete=models.CASCADE, related_name='post')
    state = CharField(default='L', max_length=1, choices=LIKE_CHOICES)
    created_at = DateTimeField(auto_now_add=True)
    updated_at = DateTimeField(auto_now=True)

    def __str__(self):
        return self.get_state_display()

据我了解,这样新闻文章根本不会与点赞相关联。我的目标是获取所有新闻文章和select_related() 的点赞。我也不想为喜欢的新闻文章创建一个新模型。我可以在这里做什么?

【问题讨论】:

  • 您是想将您的 Post 类用作其他类的“基础”模型还是一个真正有意义的类?
  • 我用它作为基础
  • 好的,给我 5 分钟,我正在写答案
  • 太好了 - 谢谢 :)

标签: python django django-models


【解决方案1】:

内容类型就是答案! https://docs.djangoproject.com/en/3.0/ref/contrib/contenttypes/

由于您的 Post 类只是其他模型的基础,您应该将其标记为抽象,因此 Django 首先不会在数据库中为其创建表:

class Post(models.Model):
  class Meta:
    abstract = True

  title = CharField(max_length=200)
  content = TextField()

  def __str__(self):
    return self.title

在您的 NewsArticle 类中:

class NewsArticle(Post):
  link = URLField(default='')
  external_id = CharField(unique=True, max_length=50, help_text='The ID of the news article from the source')
  source = CharField(max_length=15, help_text='Name of source website')
  likes = GenericRelation(Like)

在你的 Like 类中:

class Like(models.Model):
  LIKE_CHOICES = [('L', 'Like'), ('D', 'Dislike')]

  user = ForeignKey(User, on_delete=models.CASCADE)
  state = CharField(default='L', max_length=1, choices=LIKE_CHOICES)
  created_at = DateTimeField(auto_now_add=True)
  updated_at = DateTimeField(auto_now=True)

  content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
  object_id = models.PositiveIntegerField()
  content_object = GenericForeignKey('content_type', 'object_id')

  def __str__(self):
    return self.get_state_display()

【讨论】:

  • 你能解释一下这是做什么的吗?也不应该喜欢在帖子模型上?
  • 请看这里,解释的时间长但通俗易懂docs.djangoproject.com/en/3.0/ref/contrib/contenttypes
  • 如何获取所有新闻文章及其对应的like?
  • @ninesalt 查询集中第一篇新闻文章的示例查询:NewsArticle.objects.all().first().likes
  • @ninesalt 另一个例子是:article = NewsArticle.objects.all().first() Like.objects.filter(content_object=article)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-30
  • 2011-01-13
  • 1970-01-01
  • 2010-12-21
  • 2013-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多