Django OneToOneField deleting child doesn't set parents parameter as None?

276 Views Asked by At

I have two models in my Django app

class Product(models.ModelField):
  name = ...

class Discount(models.ModelField):
  product_id = models.OneToOneField(Product)

Basically, each product can have an optional discount.Now, assume I have only one product p with discount d attached. I want to delete the discount associated with the product p. So, I use

p.discount.delete()

While this makes Discount.objects.all() return [], p.discount still the associated discount object.

How do I set this attribute to None?

1

There are 1 best solutions below

0
On BEST ANSWER
p.discount = None

Changing something in the database will not affect model instances in memory. In 1.8 you can also easily reload the object from the db:

p.refresh_from_db()

Or before 1.8:

p = Product.objects.get(pk=p.pk)