DrBuck
DrBuck

Reputation: 932

Django drop downs in model

I'm currently providing choices in a dropdown in a model like this:

class FoodType(models.Model):
  type = models.CharField(max_length=30, unique=True)

  def __unicode__(self):
    return self.type

class Food(models.Model):
  name = models.CharField(max_length=30, unique=True)
  type = models.ForeignKey(FoodType)

  def __unicode__(self):
    return self.name

I did it like this rather than hardcoded choices because I want to provide an option to add/delete/change FoodTypes via the admin once the app is deployed. But then I realised once that if a FoodType is deleted that a Food is dependent on, the Food is also deleted, which I don't want. I want to be able to keep all Food records unless I explicitly want to delete one.

Is there a better way to do this that still allows the user to modify FoodTypes via the admin?

Thanks :)

Upvotes: 0

Views: 49

Answers (1)

aumo
aumo

Reputation: 5554

You can set the on_delete parameter of the ForeignKey field to a value different than CASCADE (the default value).

Ex:

type = models.ForeignKey(FoodType, null=True, on_delete=models.SET_NULL)

Upvotes: 1

Related Questions