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.
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).
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 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.
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) )
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With