Set two fields to the same value

15 views
Skip to first unread message

Jaroslav Dobrek

unread,
Jul 12, 2012, 9:51:08 AM7/12/12
to django...@googlegroups.com
Hello,

how can I design a model such that two fields are set to the same value when a new object of the type defined by the model is created?

Example:

class Test(models.Model):
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    time = start_time

Users may create Test objects in order to run their own tests. A test always starts at some date time and it always ends at some date time. Each test has a time which is increased until it equals the end time. When a user creates a new test (and before he uses it) the field time should have the same value as the field start_time.

The code above will produce a database error.

Jaroslav

luthur

unread,
Jul 12, 2012, 10:03:12 AM7/12/12
to django...@googlegroups.com
you could only assign a Field variable in the Model, "time" absolutely not a Field, the error appears. 

-- 
luthur
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/ekl9tv3zHTIJ.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

Melvyn Sopacua

unread,
Jul 21, 2012, 9:32:59 AM7/21/12
to django...@googlegroups.com
On 12-7-2012 15:51, Jaroslav Dobrek wrote:

> Users may create Test objects in order to run their own tests. A test
> always starts at some date time and it always ends at some date time. Each
> test has a time which is increased until it equals the end time. When a
> user creates a new test (and before he uses it) the field time should have
> the same value as the field start_time.

(Assuming the time field should be stored in the database)

Simplest, but specific for temporal fields:
class Test(models.Model) :
start_time = models.DateTimeField(auto_now_add=True)
end_time = models.DateTimeField(auto_now_add=True)
time = models.DateTimeField(auto_now_add=True)

Generally working:
class Test(models.Model) :
first = models.CharField(max_length=10, default='first')
second = models.CharField(max_length=10)

def __init__(self, *args, **kwargs) :
first = kwargs.get('first', False)
if not first :
first = self.__class__.first.default
second = first
if not kwargs.get('second', False) :
kwargs['second'] = second
super(Test, self).__init__(*args, **kwargs)

For the admin, see
<https://docs.djangoproject.com/en/1.4/ref/contrib/admin/#django.contrib.admin.ModelAdmin.prepopulated_fields>
for an alternate solution.
--
Melvyn Sopacua


Reply all
Reply to author
Forward
0 new messages