Hi,

I am working on ticket https://code.djangoproject.com/ticket/19580
https://github.com/django/django/pull/15318

Currently (in the patch) unsaved object raises error when trying to use reverse 
foreign key or m2m relation. (Change in FK in patch)

Other issue that is worth to consider is when saved object has nullable 
referenced field.

class Manufacturer(models.Model):
    name = models.CharField(max_length=100, null=True, blank=True, unique=True)

class Car(models.Model):
    manufacturer = models.ForeignKey(Manufacturer, null=True, blank=True, 
to_field="name")

Car().save()
m = Manufacturer()
m.save()
m.car_set.all() # returns empty QuerySet <QuerySet []>

but when we try call on this relation methods add/get_or_create/remove/clear it 
raises ValueError like M2M (Change in FK in patch)

Same case with M2M

class Pizza(models.Model):
    name = models.CharField(max_length=100, null=True, blank=True)
    
class Topping(models.Model):
    pizzas = models.ManyToMany(Pizza, through="PizzaTopping")

class PizzaTopping(models.Model):
    pizza = models.ForeignKey(Pizza, null=True, blank=True, to_field="name")
    topping = models.ForeignKey(Topping)
 
Topping().save()
p = Pizza()
p.save()
p.topping_set().all() # raise ValueError "<Pizza: Pizza object (1)>" needs to 
have a value for field "name" before this many-to-many relation can be used.

Implementation of M2M seems to be correct because behavior is consistent - in 
every case when value of referenced field is None it raises error.
See comment in similar ticket (10 years old) 
https://code.djangoproject.com/ticket/17541#comment:8

I am in doubt if suggested in the ticket solution is correct (it is 9 years 
old) because in most cases it will raise error but only when there is an 
attempt to use query there is empty QuerySet returned.
Proposal is to raise error instead return empty QuerySet in Foreign Key like 
M2M does.

Albert

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/ngqfpcasjzabfoyaclqg%40xdkw.

Reply via email to