Unexpected ForeignKey Behavior with self.pk == None
|Reported by:||Peter Sheats||Owned by:||anonymous|
|Component:||Database layer (models, ORM)||Version:||1.3|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
I'm not sure if this is technically a bug but I wanted to report it because it really surprised me today.
class Manufacturer(models.Model): name = models.CharField(blank=True, max_length=100) class Car(models.Model): manufacturer = models.ForeignKey(Manufacturer, blank=True, null=True) name = models.CharField(blank=True, max_length=100) Car.objects.create(name='Accord') Car.objects.create(name='Civic') print Manufacturer().car_set.all().count() >>> 2
Even though neither Car is related to a Manufacturer, they are both returned through the related qs. I'm assuming this is because the query looks something like this:
manufacturer = Manufacturer() Car.objects.filter(manufacturer=manufacturer.id)
I would say it is incorrect behavior to return anything through that related queryset that is not explicitly related.
Change History (26)
comment:1 Changed 5 years ago by
|Patch needs improvement:||set|
|Triage Stage:||Unreviewed → Accepted|