简体   繁体   English

如何在Django中获取子模型中存在外键的父模型的所有对象?

[英]How to get all objects of a Parent model of which foreign key exist in child model in Django?

I have 2 models 我有2个型号

#models
class Parent(models.Model):
     name = models.CharField()

class Child(models.Model)
     parentLink = models.ForeignKey(Parent)
     timeStamp = models.DateTimeField(auto_now_add=True)

I want all the objects of Parent model having foreign key mentioned in Child model and some filter on timeStamp field. 我希望Parent模型的所有对象都具有Child模型中提到的外键和timeStamp字段中的一些过滤器。

How do I do this reverse fetching of objects? 如何反向获取对象?

It's MySQL would be something like this 它的MySQL就是这样的

SELECT Parent.name FROM Parent JOIN Child on Parent.Id = Child.parentLink WHERE Child.timeStamp > '2016-01-01 : 00.00.00'

If I understand what you need correctly, it should be something like this: 如果我理解你需要什么,它应该是这样的:

Parent.objects.filter(
    child__isnull=False,
    child__timeStamp__gt=datetime.strptime(
        '2016-01-01 00.00.00',
        '%Y-%m-%d %H.%M.%S'
    )
)

This fetches all Parent objects for which there is a child whose timestamp is later than 2016/01/01. 这将获取所有Parent对象,其中有一个时间戳晚于2016/01/01的子对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在django rest框架中获取所有字段,该框架在带有外键的不同模型中被定义为相关名称? - How to get all fields in django rest framework which is defined as related name in a diffent model with foreign key? Django - 如何从具有外键的 model 中获取所有项目? - Django - How to get all items from a model that has foreign key? 通过 Django 中的子 class 验证父 model 外键 - Validate parent model foreign key by child class in Django `peewee` 如何获取外键的父 model - `peewee` how to get the parent model of a foreign key 在 Django 中创建一个 model 方法,该方法确定共享相同外键的所有对象的 ID - In Django create a model method which determines an id for all objects that share the same foreign key Django:强制一个字段对于具有相同外键的所有模型对象是唯一的 - Django: Force a field to be unique for all model objects with the same foreign key 如何在Django Rest Framwork中获得具有父模型的Forein键的子模型? - How to get child model having foregin key of parent model in Django rest framwork? 如何使用外键 django 显示来自父 model 的数据 - How to display data from parent model using foreign key django 如何使用本身是外键的字段获取Django模型的对象列表? - How to get a list of of objects of a Django model using a field that itself is a foreign key? django访问子模型父模型中的外部字段 - django access child model foreign field in parent model
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM