django ForeignKey setting allows to be empty

created at 07-16-2021 views: 1

django ForeignKey (foreign key) setting allows to be empty

for example

class Writer(models.Model):
    name=models.CharField(max_length=60,verbose_name="name")

class Books(models.Model):
    writer=models.ForeignKey('Writer',blank = True)

Requirements: It is necessary to allow the writer_id field of Books to be empty. The current writing method does not allow the writer_id to be empty.

Solution

class Writer(models.Model):
    name=models.CharField(max_length=60,verbose_name="name")

class Books(models.Model):
    writer=models.ForeignKey('Writer',blank = True,null=True)

Cause Analysis:

  1. Blank is mainly used for form validation.
  2. Null is mainly used to write to the database. The default value of null is False, which means that Django defaults that all fields need to have values before they can be written to the database normally.
Please log in to leave a comment.