简体   繁体   中英

Reverse foreign key - bug in Django?

We are using Django 1.4.13 with foreign keys - we have class BusinessUnit which inherits from a class with a foreign key to class ContentSet. We have the following function in class ContentSet:

def business_units_default_content_set_count(self):
    """
    Returns the number of business units linked to this content set as default.
    """
    return len(set([bu.pk for bu in list(self.businessunit_set.all())]))

The problem is that if we create a ContentSet without a primary key (we don't save it to disk), this function returns an integer which is not 0 (for example 30). I solved this problem by changing the function to:

def business_units_default_content_set_count(self):
    """
    Returns the number of business units linked to this content set as default.
    """
    if (self.pk):
        return len(set([bu.pk for bu in list(self.businessunit_set.all())]))
    else:
        return 0

But why do we have to check self.pk at all? Is it a bug of Django 1.4.13? And if it is, is it fixed in other versions of Django?

When you are trying to fetch all businessunit using the reverse relation django is connecting to database, filtering all the child objects by its parent.

Maybe the problem is because you have some BusinessUnits that aren't linked to any ContentSet

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