Proposal of standardize of reverse foreign key and m2m

88 views
Skip to first unread message

Albert

unread,
Feb 2, 2022, 3:17:33 PM2/2/22
to django-d...@googlegroups.com
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

Asif Saif Uddin

unread,
Feb 2, 2022, 11:21:27 PM2/2/22
to Django developers (Contributions to Django itself)

I get the following error while visiting the link

Websites prove their identity via certificates, which are valid for a set time period. The certificate for code.djangoproject.com expired on 2/3/2022.
 
Error code: SEC_ERROR_EXPIRED_CERTIFICATE
 
Reply all
Reply to author
Forward
0 new messages