[英]Django how to find if the object is referenced by ForeignKey from another class in model.py
I have two classes shown below, I wanted to add a function to File to check if the file is referenced by any data inside the Project class (similar how "was published recently" is done here: https://docs.djangoproject.com/en/4.0/_images/admin12t.png ).我有如下所示的两个类,我想将 function 添加到 File 以检查项目 class 中的任何数据是否引用了该文件(类似于“最近发布”的方式在这里完成:Z5E056C500A1goC4B6A71Z5.comdjan07B6A7110BADE.5 /en/4.0/_images/admin12t.png )。
class File(models.Model):
def __str__(self):
return self.name
file = models.FileField(upload_to='uploads/')
class Project(models.Model):
def __str__(self):
return self.name
files = models.ManyToManyField(File)
class File(models.Model):
file = models.FileField(upload_to='uploads/')
def __str__(self):
return self.name
def is_used_in_a_project(self):
return self.project_set.exists()
Django automatically exposes a <model>_set
attribute on the other side of a ManyToManyField relation. Django 自动在 ManyToManyField 关系的另一侧公开
<model>_set
属性。 This is a queryset containing all of the instances that are linked to it via the m2m relation on the other model.这是一个查询集,包含通过另一个 model 上的 m2m 关系链接到它的所有实例。
See https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_many/见https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_many/
You can alter the name of this "reverse relation" attribute by setting the related_name
of the ManyToManyField.您可以通过设置
related_name
的相关名称来更改此“反向关系”属性的名称。
https://docs.djangoproject.com/en/4.0/ref/models/fields/#manytomany-arguments https://docs.djangoproject.com/en/4.0/ref/models/fields/#manytomany-arguments
eg you could define:例如,您可以定义:
class Project(models.Model):
files = models.ManyToManyField(File, related_name="linked_projects")
class File(models.Model):
def is_used_in_a_project(self):
return self.linked_projects.exists()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.