Djang中的TextField配对

2024-04-24 23:01:06 发布

您现在位置:Python中文网/ 问答频道 /正文

(我正在写我的第一个Django应用程序,所以这个问题有点不对劲,抱歉)。你知道吗

我正在为学生创建一个类似于讲座总结的工具,我需要制作一对文本字段-讲座标题(1)和讲座总结(2)。问题是,讲座标题和讲座摘要可能需要单独的模型,因为它们有自己的字段(名称、发布日期)+我想让用户只显示讲座标题列表或搜索讲座摘要。用户可以在我的web应用程序中动态添加/删除这些讲座标题和讲座摘要。每堂课的标题都是唯一的,并且有其“课堂摘要”。你知道吗

问题是-在Django中创建文本化对的最佳方法是什么?我至少希望能收到一些关于这个想法的阅读材料的链接。。你知道吗

谢谢你!你知道吗


Tags: 工具django方法用户模型文本名称web
1条回答
网友
1楼 · 发布于 2024-04-24 23:01:06

根据您的模型的复杂性,您最好使用niekas指出的单一模型解决方案。你知道吗

但是如果你想把数据分成几个模型,你可以看看这个解决方案。你知道吗

我对Django还不是很熟练,但是实现这一点的一种方法是创建一个模型Lecture,它有两个一对一的字段LectureTitleLectureSummary。通过使用基类,可以添加一些希望所有模型都具有的字段。例如,如果您希望所有模型都有一个最后修改的DateTimeField,这是非常有用的。你知道吗

from django.db import models


class BaseModel(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True


class Lecture(BaseModel):
    title = models.OneToOneField(LectureTitle)
    summary = models.OneToOneField(LectureSummary)


class LectureTitle(BaseModel):
    name = models.TextField(max_length=30)


class LectureSummary(BaseModel):
    content = models.TextField(max_length=1000)

这可能比niekas给出的解决方案更灵活一些。你知道吗

要从LectureSummaryLectureTitle访问讲座,只需使用lecture。此字段在一对一字段的另一侧自动创建。你知道吗

要打印所有标题:

for lecture in Lecture.objects.all():
    print lecture.title.name

搜索摘要中的内容:

# search_str is the search string from user
for lecture in Lecture.objects.filter(summary.content__contains(search_str):
    print lecture.title.name

根据您的评论更新: 这应该很简单:

for lecture in Lecture.objects.all():
    #lecture.title.name gives you the title of your lecture
    #lecture.summary.content gives you the content of the lecture

相关问题 更多 >