Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Foreign Key default

I have problem with setting default value for my ForeignKey field in 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 app, and the idea is that i have an event that people can sign up for in specified groups. So I would like to be able to create event and at the same time create some groups, and then add slots to groups.

I have event field in Slot model because I need to make sure that people won't be able to sign up for 2 slots at the same time, and I also need to calculate number of slots (field in Event model). I obviously need event fields in both models to point to the same Event, so I thought that i could have something like a default value for my Slot.event.

Feel free to submit any workarounds, I can easily re-design my app. Thanks in advance for help.

EDIT: I'll try to better describe my app: it's supposed to be a calendar for an online game community (the game is arma3). I expect every event to be attended by no more than 40 people, but for our gaming sessions we need hierarchy. In particular we divide ourselfes in groups, in every group there are different roles(team leader, machine gunner, rifleman etc.). I want to have a calendar in which you can view particular event details, including groups and all the different slots, and sign up for one particular slot. I hope that it clarifies it. Please forgive all errors, English is not my first language.

I forgot to mention it earlier but I am an absolute beginner at Django and am running Django 1.7 on python 3.4. The solution with using lambda does not seem to work, here is the error log (sorry for no indentations):

(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 updated code(again there might be indentation errors, I can't get my head around 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
like image 859
badn3wz Avatar asked Dec 02 '14 14:12

badn3wz


People also ask

Can a ForeignKey have a default value?

Similarly, a Foreign Key cannot be both NOT-NULL and have a Default Value of (0).

What is ForeignKey in Django?

ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases.

Is ForeignKey in Django one to many?

To handle One-To-Many relationships in Django you need to use ForeignKey . The current structure in your example allows each Dude to have one number, and each number to belong to multiple Dudes (same with Business).

What is Related_name in Django?

The related_name attribute specifies the name of the reverse relation from the User model back to your model. If you don't specify a related_name, Django automatically creates one using the name of your model with the suffix _set. Syntax: field_name = models.Field(related_name="name")


1 Answers

I had a similar problem trying to add a foreign key to a migration without a default value. Remove the lambda expression and let the default value as nullable (None) and try again with the following code sample. It worked perfectly for me.

e.g:

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 omitted the non interesting fields on models for the sake of simplicity. I hope it could help you.

like image 66
mannysz Avatar answered Oct 16 '22 08:10

mannysz