简体   繁体   中英

filter by foreign key in django models

Let's say I have following models:

class VKLink(models.Model):
    user_id = models.IntegerField()
    name = models.CharField(max_length=200)


class BaseComment(models.Model):
    owner = models.ForeignKey(VKLink)
    from_id = models.IntegerField(default=0)
    text = models.CharField(max_length=3000)

    def is_own(self):
        return self.from_id == self.owner.user_id

BaseComment is counted as 'own comment' if from_id equals to links user_id. I want to get all BaseComments that are 'own'. How can I select it in django models term?

BaseComment.objects.filter(from_id=owner__user_id) does not work, as owner__user_id is not defined at that stage.

您可以使用F()表达式

BaseComment.objects.filter(from_id=F('owner__user_id'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM