Search code examples
djangodjango-modelsdjango-views

Django - Get a list of the items for which values exist


I have a project in Django. I have 2 modules, QlikApp and QlikAppUserAccess that are related to a ForeignKey.

I want to get all the apps that have related 'Qlik AppUser Access' data.

How can i do that?

class QlikApp(models.Model):
    id = models.CharField(
        verbose_name="App ID",
        primary_key=True,
        max_length=100,
        null=False,
        blank=False,
    )
    application_name = models.CharField(
        verbose_name="Qlik app name",
        max_length=100,
        blank=False,
        null=False,
    )

    def __str__(self):
        return f"{self.application_name}"


class QlikAppUserAccess(models.Model):
    app = models.ForeignKey(
        QlikApp,
        related_name="qlik_app_user",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
    )
    employee = models.ForeignKey(
        Employee,
        related_name="employee_app_access",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
    )
    access_type_dropdown = (
        ("ADMIN", "ADMIN"),
        ("USER", "USER"),
    )
    access_type = models.CharField(
        verbose_name="Access Type",
        max_length=30,
        blank=True,
        null=True,
        choices=access_type_dropdown,
    )

    def __str__(self):
        return f"{self.app.application_name} - {self.employee.employee_user_name} - {self.access_type}"

For example: I have 10 apps but only 2 of them have related data and I wanna show inly them.

For example: I have 3 apps:

  1. app1
  2. app2
  3. app3

I have 2 values in QlikAppUserAccess model.

  1. Roni -> related to app1
  2. Avi -> related to app2

So i need to see only app1 and app2.

Thanks a lot.


Solution

  • You filter with:

    QlikApp.objects.filter(qlik_app_user__isnull=False).distinct()

    This will make a query like:

    SELECT DISTINCT qlikapp.*
    FROM qlikapp
    INNER JOIN qlikappuseraccess ON qlikappuseraccess.app_id = qlikapp.id

    and thus only retrieve qlikapp items for which there is at least one qlikappuseraccess record.