Django Queryset foreign keys

做~自己de王妃 提交于 2021-01-07 03:12:39

问题


I am trying to get a queryset but it is not displaying anything. Basically, I want to get the Asset objects that are assigned via foreign key to an employee, which is a foreign key of the signed in user.

views.py

def get_queryset(self):
        assetlist = Asset.objects.filter(organisation__employee__user=self.request.user)
        print(assetlist)
        return assetlist

models.py

class Employee(models.Model):
    name = models.CharField("Employee Name", max_length=50, blank=False)
    email = models.CharField("Employee Email", max_length=50, blank=True)
    user = models.ForeignKey(User)
    clientID = models.ForeignKey(Organisation)

    def save(self):
        self.name = self.user.get_full_name()
        self.email = self.user.email
        super(Employee, self).save()

    def __str__(self):
        return self.name


class Asset(models.Model):
    name = models.CharField("Asset Name", max_length=30, primary_key=True)
    organisation = models.ForeignKey(Organisation)

    def __str__(self):
        return self.name


class Organisation(models.Model):
    name = models.CharField("Organisation Name", max_length=50, blank=False)
    location = models.TextField("Organisation Address", max_length=200, blank=True)
    tel = models.CharField("Telephone Number", max_length=20)

    def __str__(self):
        return self.name

回答1:


The answer was to approach from another model, as seen below:

assetlist = Sensor.objects.filter(asset__organisation__employee__user=self.request.user)



回答2:


There is no employee field inside organisation. It's an reversed relation, there are many employees attached so you can't query it like that.

But there is something called related_name in django foreign keys, with use of that, your query should look like that:

    assetlist = Asset.objects.filter(organisation__employee_set__user=self.request.user)

or if you specify your own related_name into employee -> organisation relation:

clientID = models.ForeignKey(Organisation, related_name="employees")

it will look like this:

    assetlist = Asset.objects.filter(organisation__employees__user=self.request.user)



回答3:


You have written wrong code. You want an Asset object by using:

assetlist = Asset.objects.filter(organisation__employee__user=self.request.user)

But you clearly can see in your models.py that there is no relationship between Organisation and Employee, then how can you get a result using organisation__employee...?

You should first create a ForeignKey field to relate with Employee model then your code will work fine.



来源:https://stackoverflow.com/questions/32067851/django-queryset-foreign-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!