Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you specify a default for a Django ForeignKey Model or AdminModel field?

How can I set a default value on a ForeignKey field in a django Model or AdminModel?

Something like this (but of course this doesn't work)...

created_by = models.ForeignKey(User, default=request.user) 

I know I can 'trick' it in the view, but in terms of the AdminModel it doesn't seem possible.

like image 284
T. Stone Avatar asked Jun 02 '09 04:06

T. Stone


People also ask

What is default in Django model?

default: The default value for the field. This can be a value or a callable object, in which case the object will be called every time a new record is created. null: If True , Django will store blank values as NULL in the database for fields where this is appropriate (a CharField will instead store an empty string).

What is the default primary key in Django?

If you don't specify primary_key=True for any fields in your model, Django will automatically add an IntegerField to hold the primary key, so you don't need to set primary_key=True on any of your fields unless you want to override the default primary-key behavior. For more, see Automatic primary key fields.

What is Django ForeignKey model?

What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it's used to create many-to-one relationships within tables. It's a standard practice in relational databases to connect data using ForeignKeys.


2 Answers

class Foo(models.Model):     a = models.CharField(max_length=42)  class Bar(models.Model):     b = models.CharField(max_length=42)     a = models.ForeignKey(Foo, default=lambda: Foo.objects.get(id=1) ) 
like image 64
Daniel Magnusson Avatar answered Sep 22 '22 14:09

Daniel Magnusson


For django 1.7 or greater,

Just create an ForeignKey object and save it. "default" value can be the id of the the object that should be linked by default.

For example,

created_by = models.ForeignKey(User, default=1) 
like image 20
Rahul Reddy Vemireddy Avatar answered Sep 20 '22 14:09

Rahul Reddy Vemireddy