Django - default for foreign key

I have a problem setting the default value for my ForeignKey field in the model. Here is my code:

class Group(models.Model): name = models.CharField(max_length=50) event = models.ForeignKey(Event) def __str__(self): return self.name class Slot(models.Model): title = models.CharField(max_length=50, blank = True) name = models.ForeignKey(SlotName) is_taken = models.BooleanField(default=False) usr = models.ForeignKey('auth.User', blank=True, null=True) group = models.ForeignKey(Group) event = models.ForeignKey(Event) #i would like to have something like "default=group.event" here def __str__(self): return self.name.name 

This is a simple calendar application, and the idea is that I have an event in which people can register in certain groups. Therefore, I would like to create an event and at the same time create several groups, and then add slots to the groups.

I have an event field in the Slot model, because I have to make sure that people cannot register for 2 slots at the same time, and I also need to calculate the number of slots (field in the event model). I explicitly need the event fields in both models to point to the same event, so I thought that I might have something like the default value for my Slot.event.

Feel free to suggest any workarounds, I can easily redesign my application. Thank you in advance.

EDIT: I will try to better describe my application: it should be a calendar for the online gaming community (the game is arma3). I expect that no more than 40 people will be present at each event, but for our gaming sessions we need a hierarchy. In particular, we divide ourselves into groups, in each group there are different roles (team leader, machine gunner, gunner, etc.). I want to have a calendar in which you can view information about a specific event, including groups and all different slots, and register in one specific slot. I hope he makes this clear. Please forgive all errors, English is not my first language.

I forgot to mention this before, but I am an absolute newbie to Django and am running Django 1.7 on python 3.4. The solution using lambda doesn't seem to work, here is the error log (sorry for the lack of indentation):

 (own) qwe@qwe :~/Projects/own/src$ python manage.py makemigrations Migrations for 'cal': 0021_auto_20141202_1913.py: - Remove field title from slot - Alter field event on slot Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/qwe/Projects/own/lib/python3.4/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line utility.execute() File "/home/qwe/Projects/own/lib/python3.4/site-packages/django/core/management/__init__.py", line 377, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/qwe/Projects/own/lib/python3.4/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **options.__dict__) File "/home/qwe/Projects/own/lib/python3.4/site-packages/django/core/management/base.py", line 338, in execute output = self.handle(*args, **options) File "/home/qwe/Projects/own/lib/python3.4/site-packages/django/core/management/commands/makemigrations.py", line 124, in handle self.write_migration_files(changes) File "/home/qwe/Projects/own/lib/python3.4/site-packages/django/core/management/commands/makemigrations.py", line 152, in write_migration_files migration_string = writer.as_string() File "/home/qwe/Projects/own/lib/python3.4/site-packages/django/db/migrations/writer.py", line 129, in as_string operation_string, operation_imports = OperationWriter(operation).serialize() File "/home/qwe/Projects/own/lib/python3.4/site-packages/django/db/migrations/writer.py", line 86, in serialize arg_string, arg_imports = MigrationWriter.serialize(arg_value) File "/home/qwe/Projects/own/lib/python3.4/site-packages/django/db/migrations/writer.py", line 310, in serialize return cls.serialize_deconstructed(path, args, kwargs) File "/home/qwe/Projects/own/lib/python3.4/site-packages/django/db/migrations/writer.py", line 221, in serialize_deconstructed arg_string, arg_imports = cls.serialize(arg) File "/home/qwe/Projects/own/lib/python3.4/site-packages/django/db/migrations/writer.py", line 323, in serialize raise ValueError("Cannot serialize function: lambda") ValueError: Cannot serialize function: lambda 

Here is the updated code (again, there may be indentation errors, I cannot describe this code system here):

 class Event(models.Model): author = models.CharField(max_length=200) title = models.CharField(max_length=200) details = models.TextField(max_length=5000) slots_no = models.PositiveIntegerField(default=0, editable=False) created_date = models.DateTimeField( auto_now=True) event_date = models.DateField( blank=True, null=True) event_time = models.TimeField(default='20:00') created_by = models.ForeignKey('auth.User') type = models.ForeignKey(EventType) def publish(self): self.save() def __str__(self): return self.title class Group(models.Model): name = models.CharField(max_length=50) event = models.ForeignKey(Event) def __str__(self): return self.name class Slot(models.Model): #title = models.CharField(max_length=50, blank = True) name = models.ForeignKey(SlotName) is_taken = models.BooleanField(default=False) usr = models.ForeignKey('auth.User', blank=True, null=True) group = models.ForeignKey(Group) event = models.ForeignKey(Event) def __str__(self): return self.name.name 
+5
source share
2 answers

I had a similar problem trying to add a foreign key to a migration without a default value. Remove the lambda expression and set the default value to NULL and try again using the following code example. This worked great for me.

eg:

 from django.db import models class Slot(models.Model): event = models.ForeignKey('Event', null=True) group = models.ForeignKey('Group', null=True) def save(self, *args, **kwargs): if(self.group is not None and self.group.event is not None): self.event = self.group.event super(Slot, self).save(*args, **kwargs) class Event(models.Model): name = models.CharField(max_length=100) class Group(models.Model): name = models.CharField(max_length=100) event = models.ForeignKey('Event') 

I just omitted the non-zero margins on the models. Hope this helps you.

+3
source

Something like what daniph suggested should work:

 event = models.ForeignKey(Event, default=lambda: self.group.event if self.group else None) 

Now, if I understand you, events are created for certain groups, and these events have slots that users can use to register for the event.

I would handle this as follows:

 class Event(models.Model): group = models.ForeignKey(Group) class Group(models.Model): name = models.CharField(max_length=50) class Slot(models.Model): title = models.CharField(max_length=50, blank = True) name = models.ForeignKey(SlotName) is_taken = models.BooleanField(default=False) usr = models.ForeignKey('auth.User', blank=True, null=True) event = models.ForeignKey(Event) 

This method makes more sense and duplicate foreign keys do not exist. Your slot knows what the event is, and the event knows its owner group.

You can cancel the request, for example:

Slots for my event:

 my_event.slot_set.all() 

Events for my group:

 my_group.event_set.all() 

For unrelated advice, do not use the user model of the user. The correct way to use it is in the documentation .

 from django.conf import settings from django.db import models class Article(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL) 

If you need to use a different user model in the future, your application will not break if you do it this way.

Edit:

I misunderstood a couple of things. Events seems to have several groups and groups having multiple slots. Now "have multiple" can be represented using a foreign key.

In this case, the group must have a foreign key for events, and the slots must have a foreign key for groups. You can check which event for a specific slot has:

 my_slot.group.event 
0
source

Source: https://habr.com/ru/post/1208154/


All Articles