I have an existing model in which I want to add a User foreign key ex:
user = models.ForeignKey(User, unique=False)
If I set the parameter default=User.admin I get an attribute error.
If I try to set default=User.objects.get(username='admin') I get the error ValueError: Cannot serialize: <User: admin>
How can I set the default to be the User named admin or any other user?
Did you try setting primary key? The user table uses integers for the primary key.
Related
I want to add 'status' field in my django auth_user table, Please let me know how i can add this field. I was trying to add by signup form but i am unable to migrate from there, I am getting error.
Is there are any other option where i can add this field in Django default login functionality.
hey you will have to overide the you model.You can add multiple new column
class User(AbstractBaseUser, PermissionsMixin, BaseModelMixin):
status = models.CharField(max_length=12)
and setting file you have to add the
AUTH_USER_MODEL = "accounts.User"
You can inherith a model from AbstractBaseUser class. It provides the core implementation of a user model, including hashed passwords and tokenized password resets. According to the official documentation: https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#specifying-a-custom-user-model
class MyUser(AbstractBaseUser):
status= models.CharField(max_length=40)
...
How to set username as ForeignKey in Django module.
is bellow method is correct?
user = models.ForeignKey(User, db_column="user")
i cannot use ID as ForeignKey because my old db have username as ForeignKey.(I need to migrate the the old Data)
Use below code:
user = models.ForeignKey(User, to_field="username")
The field on the related object that the relation is to. By default,
Django uses the primary key of the related object. If you reference a
different field, that field must have unique=True.
I am currently working on a Django project.
I am using Foreign Fields in one of the models.
class Purchase (models.Model):
user = models.ForeignKey(User, blank = True, null = True)
game = models.ForeignKey(Game)
...
And accessing these values in views like
p = Purchase.objects.filter(user=request.user,game=request.POST['gameid'])
In DB(i am using Postgres), the fields in Purchase Table are user_id and game_id
respectively for user and game.
I think its the Django default to suffix foreign fields with _id.
So i tried a bit in manage.py shell
and i came to know that i am getting same amount of results even if i use
p = Purchase.objects.filter(user_id=request.user,game_id=request.POST['gameid'])
So my doubt is that whether the field names defined in model and exact names of those fields in DB can be used interchangeably? Any further information or explanation would be appreciated.
Thanks
Django does this for foreign key fields. If you want to have the same name in the database then you can define column name using db_column:
user = models.ForeignKey(User, db_column='user')
P.S you can use both user_id and user to reference foreign key. This is absolutely fine. But i will suggest you to use model level names to avoid confusions.
I have one app in which a model extends the User mode.
class ExtendedUser (models.Model):
user = models.ForeignKey(User)
favorite_color = models.CharField(...
#...
I have another app that also has a foreignkey with the user model.
I wanted to know how can I access all the information related to a particular user?
My problem comes when I try to make inverse relationships (I think), here is what I try:
>>from django.contrib.auth.models import User
>>from firstapp.models import ExtendedUser
>>a = User.objects.get(pk=1)
>>a
<User: username1>
>>b = a.favorite_color
AttributeError: 'User' object has no attribute 'favorite_color'
>>c = ExtendedUser.objects.get(pk=1)
>>c
<User: username1>
>>c.favorite_color
<Favorite_color: blue>
The problem is when I am on "a" I cannot access the extended model information on the user, such as "favorite_color", and when I am on "c" I cannot access the User model native info such as email or perms. Is there a way to do this?
And also,
Is there a way where I can pick one user id and see all the fields (from all models and apps) that are related to that object?
But this isn't "extending the user model" at all. You have a reference to a completely different model, via a ForeignKey. I don't know why you'd expect favorite_color to suddenly become an attribute on the User model.
Instead of a ForeignKey (which implies many ExtendedUsers for each User), use a OneToOneField. Then you can follow the relationship directly:
user = User.objects.get(pk=1)
print user.extendeduser.favorite_color
I have created a model which has foreign key to the django.contrib.auth.models User model. I need to retrieve the value the foreign key is referring to. But how to do that?
E.g. my model is
from django.contrib.auth.models import User
def FooModel(models.Model):
user = models.ForeignKey(User)
then I know I can either use:
FooModel.objects.get() or FooModel.objects.filter() but as far as I know they will only return entries from the FooModel only. So how do I retrieve from the User model?
m = FooModel.objects.get(id=123434)
m.user.username
You can use ..That wxample will return you the username of the related user. Also you can create joins using __ on the query filtering. Like:
FooModel.objects.get(user__username='Foo')
But, since you are building your query on FooModel, you will always get FooModel results. So you have you use . to use foreignkey relations to get to the required User field.
EDIT:
Django also allows you to use reverse relations on querysets, so even though User model do not have a foreignkey to FooModel on its model structure, you can use reverse relation of Foomodel.user foreignkey like:
def FooModel(models.Model):
user = models.ForeignKey(User)
foofield = Models.CharField(...)
User.objects.get(foomodel__foofield='Beatles')
will return you the user which have FooModel record with a foreign key to his User record and foofield value of Beatles
You can access foreign key ids by referencing the property name + _id. For example: yourmodel.user_id