《python从入门到实践》Django章节——关于entry_set的坑

《Python从入门到实践》Django章节中,有一个视图

def topic(request,topic_id):
   topic = Topic.objects.get(id=topic_id)
   entries = topic.entry_set.order_by('-date_added')
context={'topic':topic,'entries':entries}

    return render(request,'learning_logs/topic.html',context)

注意,上面代码这里有一个关键的地方:entries = topic.entry_set.order_by(’-date_added’).这个entry_set不是一个固定的属性变量。这句代码的作用是根据topic的具体内容,获取该topic下的所有Entries。但是topic之所以能够调用entry_set不是因为Topic.objects的返回对象有一个属性变量叫entry_set,而是因为你在models.py中定义了一个class Entry()模型。而且Entry模型定义了topic是外键。所以这里的entry_set的entry指的是Entry模型的名字。比如,我现在在自己的app里的models.py中定义了两个模型:
class Train_Type()、class Train_Items()。Train_Items的外键是Train_Type。我现在想在HTML中点击一个训练类型,就显示该训练类型下所有的训练课目。那么,此时你可以这样定义视图函数:

def train_type(request,train_type_id):
    train_type = Train_Type.objects.get(id=train_type_id)
    train_items = train_type.train_items_set.order_by('item_number')
    context = {'train_type':train_type,'train_items':train_items}
    return render(request,'train_plan/train_type.html',context)

同样是先获取特定的训练类型,然后调用train_items_set,而不是entry_set。

你可能感兴趣的:(Python)