Django:外键查询 [英] Django: foreign key queries

查看:340
本文介绍了Django:外键查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Django,并尝试在桥接表中查询外键。道歉,如果这是一个重复的,我没有能够通过搜索找到答案。我有模型定义如下

I'm learning Django and trying to get the hang of querying foreign keys across a bridging table. Apologies if this is a duplicate, I haven't been able to find the answer by searching. I've got models defined as follows

class Place(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=100)
class PlaceRef(models.Model):
    place = models.ForeignKey(Place) # many-to-one field
    entry = models.ForeignKey(Entry) # many-to-one field
class Entry(models.Model):
    id = models.IntegerField(primary_key=True)
    name =  models.CharField(max_length=10)

如果我想检索与特定地点相关联的所有条目,我该怎么做?

If I want to retrieve all the Entries associated with a particular Place, how do I do it?

place = get_object_or_404(Place, id=id)
placerefs = PlaceRef.objects.filter(place=place)
entries = Entry.objects.filter(id.....)

另外,如果在Django中定义(或摆脱)PlaceRefs有一个更明智的方法,请随意提出替代方案。

Also, if there is a more sensible way for me to define (or get rid of) PlaceRefs in Django, please feel free to suggest alternatives.

感谢您帮助初学者!

推荐答案

'建议将模型重写为:

First, I'd suggest rewriting the models to:

class Place(models.Model):
  id = models.IntegerField(primary_key=True)
  name = models.CharField(max_length=100)
class Entry(models.Model):
  id = models.IntegerField(primary_key=True)
  name =  models.CharField(max_length=10)
  places = models.ManyToManyField(Place, related_name='places')

所以你可以查询:

Entry.objects.filter(places__id=id)

在您当前的模型中:

Entry.objects.filter(placeref_set__place__id=id)

请注意,双下划线 __ 用于从一个模型跳转到下一个模型。此外,django在模型上创建一些可帮助您导航到相关对象的字段。在这个例子中: Entry.placeref_set 。您可以在这里阅读更多信息:

Note that the double underscore __ is used to jump from one model to the next. Also, django creates some fields on the model that help you navigate to related objects. In this example: Entry.placeref_set. You can read more about it here:

http://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward

这篇关于Django:外键查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆