Re: Django ORM: default value from sql query
I don't think that will work because the default value is unrelated to a specific instance of a model and you want it to depend on the instance if I'm not mistaken. Once the instance exists, we're past the point where a default value will be used.
-- I think you'll have to handle this in a view.
On Wednesday, August 21, 2013 8:07:51 PM UTC-7, Marcin Szamotulski wrote:
On Wednesday, August 21, 2013 8:07:51 PM UTC-7, Marcin Szamotulski wrote:
I should be more specific: I cannot because the query depends on the
object instance:
class MyModel(models.Models):
fkey = models.ForeignKey(..., null=False)
count = models.PosotiveIntegerField(default=lambda:MyModel. objects.filter(fkey_id= _?_ ).count())
where _?_ should be the models's instance fkey attribute.
On 17:05 Wed 21 Aug , Simon Charette wrote:
> You can achieve this by setting a callable default value [1] on you field:
>
> class MyModel(models.Model):
> count =
> models.PositiveIntegerField(default=lambda:MyModel. objects.count())
>
> [1]
> https://docs.djangoproject.com/en/dev/ref/models/fields/# django.db.models.Field.default
> Le mercredi 21 ao�t 2013 18:49:48 UTC-4, Marcin Szamotulski a �crit :
> >
> > Dear Django users,
> >
> > I am would like to set a default value on a model's field as a result of
> > a simple query. Something that in SQLAlchemy is done like that:
> > http://docs.sqlalchemy.org/en/rel_0_7/core/schema.html#sql- expressions
> >
> > Specifically I want to count some objects in the database and set this
> > count as the default value. I know that this can be done in two steps
> > first find the value then set it, but I would like to have it done
> > automatically.
> >
> > Best regards,
> > Marcin
> >
>
> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com .
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users .
> For more options, visit https://groups.google.com/groups/opt_out .
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home