简体   繁体   中英

Django model inheritance: how to retrieve records?

I have these Django models:

class Base(models.Model):
    name = models.CharField(max_length=255)

class Restaurant(Base):
    pass

class Hotel(Base)
    pass

class Message(models.Model)
    text = models.TextField()
    parent = models.ForeignKey(Base, on_delete=models.CASCADE)

I would like to set up a query to retrieve all of the messages left about Hotels only. But how to do that?

Message.objects.filter(has_attr("Hotel"))

Obviously this doesn't work but something like that is what I am looking for.

An inherited model has an implicit OneToOneField from the child to the parent. This relation in reverse has, by default, as related name the name of the class, so hotel .

We thus can check if there exists a Hotel object for the given parent with:

Message.objects.filter()

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