Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ).

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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. This is a queryset containing all of the instances that are linked to it via the m2m relation on the other model.

See 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.

https://docs.djangoproject.com/en/4.0/ref/models/fields/#manytomany-arguments

e.g. 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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading