djangopostgresqldjango-modelsdjango-postgresql

Is it possible to have a model reference many other models depending on the situation in django?


I honestly don't know how to even phrase my question but i think an example might help.

I have mad three apps with their own models respectfully. App1, App2, App3. I want to create a new app (Reports) which will report on each of my other apps (App1,App2,App3). With my current knowledge i have the following in my Reports models.py

class Reports(models.Model):
    name = models.CharField(max_length=150, blank=True)

    app1_reported = models.ForeignKey(
        App1, on_delete=models.CASCADE, related_name='reported_app1', blank=True)

    app2_reported = models.ForeignKey(
        App2, on_delete=models.CASCADE, related_name='reported_app2', blank=True)

    app3_reported = models.ForeignKey(
        App3, on_delete=models.CASCADE, related_name='reported_app3', blank=True)

is there any way for me to create in my Reports model one reference that could reference either App1, or App2, or App3? something like:

class Reports(models.Model):
    name = models.CharField(max_length=150, blank=True)

    reported = models.ForeignKey(
        App1 or App2 or App3, on_delete=models.CASCADE, related_name='reported_app_is', blank=True)

My app works fine with the first implementation I would just like to know if there is a better way. Also please let me know if this makes sense, im struggling with the right wording.


Solution

  • You can use the contenttypes framework. Here is a link for your reference