-1

I have two models

class League(models.Model):
   league_id = models.IntegerField(primary_key=True)

class Fixture(models.Model):
   league_id = models.ForeignKey('League',null=True, on_delete=models.SET_NULL)

Fixture model relate on League model with league_id foreign key field. I want to create objects of Fixture class and when i trying to create them i understand that i can't to do it because my fixture model relate to league model which hasn't values. I googled about this problem and found that it is most popular problem in Django. Can anyone give me advise how i should create this kind of objects which refer on doesnt exist objects

1 Answers1

0

Add blank=True to your league_id field definition:

league_id = models.ForeignKey('League',null=True, blank=True, on_delete=models.SET_NULL)

Also, you should name that field league vs league_id. It holds a reference to a League model, not just the id.

Shane
  • 613
  • 6
  • 15
  • If i am understand my problem can be solved with adding blank=True but i didn't understand why i should specify blank=True in foreign key field indeed in primary key field. Also i didn't understand your note about league_id can you explain your note more deep? – Наглый Спамер Nov 01 '19 at 20:53
  • You need to have blank=True for Django form validation purposes. If it's not set to allow a blank value, then using a form - say via Django Admin panel - will require you to enter a League. Here is a good answer on the different combinations and what their effects are: https://stackoverflow.com/questions/8609192/differentiate-null-true-blank-true-in-django It expands a bit more than the Django docs as far as how the blank keyword affects things, but you can read the docs direct here: https://docs.djangoproject.com/en/2.2/ref/models/fields/#blank – Shane Nov 01 '19 at 21:38
  • As for `league` over `league_id` - let's assume you have some League objects and Fixture objects. If you grab all fixtures via `fixtures = Fixture.objects.all()`, each fixture object will have a reference to its corresponding League object. So you have do `fixture[0].league`, you get an actual League object to operate on, not just the id for that league. – Shane Nov 01 '19 at 21:40