我发现django外键有点令人困惑,是否有任何方法可以使用单个查询来实现下面的视图?

# Model
class Programme(models.Model):
    name = models.CharField(max_length = 64)

class Actor(models.Model):
    programme = models.ForeignKey(Programme)
    name = models.CharField(max_length = 64)


# View
def list_actors( request, programme_id):
    programme = Programme.objects.filter(id = programme_id)[0]
    actors = Actor.objects.filter(programme = programme_id)
    json = simplejson.dumps( [{
        'name': str(actor.name),
        'rating': str(actor.rating),} for actor in actors] )
    return HttpResponse(json, mimetype='application/javascript')

最佳答案

您查询Programme并分配给programme,但在任何地方都不会使用结果。把那根线取下来。

关于python - Django - 在单个查询中获取外键对象?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2367747/

10-13 04:48