Ask Your Question
1

Write a query using user object to get data from different table

asked 2013-06-05 12:35:33 -0600

SocialQA gravatar image

I have created a new table which has auth_user table id as its foreign key. My new table has extra information of the user which I want to populate on the profile page of the user.

Here is the model of the new table:

class ShibUser(models.Model):
    auth_user = models.ForeignKey(User)
    shib_username = models.CharField(max_length = 200)
    shib_user_role = models.CharField(max_length = 200)

    class Meta:
        app_label = 'askbot'

Basically way I understand is that write the query but use objects. So I initially started by adding a field in the edit profile:

in askbot/forms.py

role = forms.CharField(
                    label=_('Role'),
                    required=False,
                    max_length=255,
                    widget=forms.TextInput(attrs={'size': 35})
                )

my next goal was to get the user role which is in the new table that I created based on the id of the auth_user table.

if askbot_settings.EDITABLE_SCREEN_NAME:
    self.fields['role'].initial = "test"

Currently I have put dummy "test", How can I accomplish this?

edit retag flag offensive close merge delete

Comments

Which form are you modifying?

Evgeny gravatar imageEvgeny ( 2013-06-06 06:44:21 -0600 )edit

1 Answer

Sort by ยป oldest newest most voted
0

answered 2013-06-06 06:42:34 -0600

Evgeny gravatar image

updated 2013-06-06 06:53:30 -0600

It's achieved via "related name". Django adds one automatically for each relational field of the models.

In this case one could do:

u = User.objects.get(id=1)
shib_profile = u.shibuser_set.all()[0]
shib_profile.shib_user_role = 'captain'
shib_profile.save()

or:

u.shibuser_set.all().update(shib_user_role='captain')

If you don't like name shibuser_set, create your own with the related_name parameter in the model field definition (see django docs for that).

Most importantly I would recommend you to define that extra model in a separate app. If it's inside askbot code base, it may be harder down the road to keep the code in sync. It will be also more difficult this way to identify bugs as you will be reporting bugs against your custom code base and we may not be able to verify and help you.

It's not a good idea at all to modify askbot/forms.py, much easier to create an app say askbot_shib and define a separate form there.

Then - if adding that form to askbot is not yet available by configuration, we can build such capability. It's already possible to define custom "ask" and "answer" forms and we can have more.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2013-06-05 12:35:33 -0600

Seen: 53 times

Last updated: Jun 06 '13