On Sat, Oct 10, 2009 at 6:04 PM, Senthil <senthil.prem...@gmail.com> wrote:

>
> Hey Guys,
> I am not able to understand this behavior happening in django
>
> My models.py is as follows
>
> from django.db import models
> from django.contrib.auth.models import User
>
>
> class ht_wt(models.Model):
>        user = models.ForeignKey(User)
>        EntryDate = models.DateField(auto_now = True)
>        height = models.IntegerField(verbose_name = 'Users height at that
> given date')
>        weight = models.IntegerField(verbose_name = 'Users Weight at that
> given date')
>        #userid = models.CharField(max_length = 50,verbose_name =
> 'UserName',blank = False)
>
>        def __unicode__(self):
>                return 'Table to capture the users height & weight at the
> given
> date'
>

Note this is a rather odd __unicode__ method.  This method is used to get
the string representation of an instance of the model, not the model class
overall.  Usually you'd want to return specific attributes from the model
instance self, so that you can tell which instance you are dealing with.
With what you have here all model instances of this class will appear the
same from their string/unicode representation.


> class food_log(models.Model):
> [snip model that doesn' t have anything to do with the question]
>
> I try query a user from the existing  user table and save that user to
> a new ht_wt model object and save that object and I get an error
> saying that it cannot recognize the users primary key. However, when I
> save a new user and use that in my ht_wt model object, then everything
> works fine as shown below.
>
> >>> from django.contrib.auth.models import User
> >>> from htrack.htapp.models import *
> >>> u = User(username='testuser')
> >>> u
> <User: testuser>
>

You have not actually retrieved a user from the existing user table here.
What you have done is created a new User model instance with username
'testuser'.  This instance has not been saved to the database so it has no
primary key id.

If you want to retrieve an instance from the database you need to use one of
the model methods that actually accesses the database.  For example:

>>> u = User.objects.get(username='testuser')

Assuming that works (there is a User with that username), your subsequent
code will work.

Karen

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to