我有两个模型,一个与外键相关:
Foo foo; // a foo object
foo.setFooFunction(o); // pass it the boost::python::object
在class Service(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class ServiceFile(models.Model):
service_file = models.CharField(max_length=100)
service = models.ForeignKey(Service)
内,我想抓取views.py
内容及其多个Service
值(以便将其与上下文一起传递给模板)。我怎么能这样做?
答案 0 :(得分:3)
service = Service.objects.get(id=111) # service whose id is 111 for example
serv_files = ServiceFile.objects.filter(service=service)
答案 1 :(得分:2)
您只需在上下文中获取Service
,即可通过您可以直接在模板中创建的查询来访问ServiceFile
。例如,您的上下文包含all_services
Service.objects.all()
。然后,在您的模板中:
// iterate over each service
{% for service in all_services %}
// _set.all gets all ServiceFile objects that have a
// specific service as foreign key.
{% for servicefile in service.servicefile_set.all %}
// You can access properties of each of these servicefiles.
{{ servicefile.service_file }}