django 如何在一个模型中有效地预取多个列?

8ljdwjyq  于 2023-01-06  发布在  Go
关注(0)|答案(1)|浏览(149)

我不确定我预取项目集的方法是否正确,它的嵌套反向外键获取(另一个模型对象和其他对象)。

class Created(models.Model):
    created = models.DateField(default=timezone.now)

    class Meta:
        abstract = True

class Category(Created):
    category = models.CharField(unique=True, max_length=200)

class Question(Created):
    question = models.CharField(unique=True, max_length=200)
    category = models.ForeignKey(
        Category, on_delete=models.CASCADE, related_name="questions"
    )

    @property
    def correct_answer(self):
        return self.questions.filter(correct=True)

class Answer(Created):
    name = models.CharField(max_length=200)
    correct = models.BooleanField(default=False)
    question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="answers")

查询:
第一个月
上面的陈述给了我3个问题,我认为这是太多了。或者也许这是好的?感谢任何反馈:)

mzsu5hc0

mzsu5hc01#

我稍微修改了你的代码,在category类中添加了DateTimeField并继承了models.Model,我还删除了correct_answer方法,因为如果你想获取问题或答案对象,你不能在你以前创建的类对象中定义一个函数。

from django.db import models

# Create your models here.
class Created(models.Model):
    created = models.DateTimeField('date published')

    class Meta:
        abstract = True 

class Category(models.Model):
    category = models.CharField(unique=True, max_length=200) 
    
class Question(Created):
    question = models.CharField(unique=True, max_length=200)
    category = models.ForeignKey(
        Category, on_delete=models.CASCADE, related_name="questions")
    
class Answer(Created):
    name = models.CharField(max_length=200)
    correct = models.BooleanField(default=False)
    question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="answers")

在这个例子中,我想展示对象已经正确定义了他的方法和字段,我当然不知道你为什么要使用correct_answer,但是如果你想得到一个有特定值的对象,比如correct变量,你可以使用filter方法得到一个QuerySet示例。
交互解释程序

>>> from .models import *
>>> from django.utils import timezone
>>> category = Category.objects.create(category="normal")
>>> question = Question.objects.create(question="text", category=category, created=timezone.now())
>>> answer = Answer.objects.create(name="name", correct=True, question=question, created=timezone.now())
>>> answer.created
datetime.datetime(2023, 1, 4, 7, 15, 30, 899071, tzinfo=datetime.timezone.utc)
>>> Answer.objects.filter(correct=True)
<QuerySet [<Answer: Answer object (1)>]>
>>> Category.objects.prefetch_related("questions", "questions__answers")[0].category
'normal'

相关问题