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.
Related
I have a model which is named Client. It's defined in models in part as the following:
class Client(models.Model):
username = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
I've run makemigrations and migrations, but when I create a new client object and try to save it from forms I get and Integrity Error: NOT NULL constraint failed: intake_client.username_id.
username_id is the field name Django automatically generates with the migration, but saving these forms results in this field containing a null value and is not being generated automatically as a dependency by Django. If I set primary key to true in the username, it works ok, but then I have problems deleting the objects because Django says the model does not have an id field (since it is now changed to username_id). Why is Django not generating and putting the dependency values in the username_id field automatically when the instance is saved?
I currently have a Django powered in-production web app that contains multiple models, sitting on top of a Postgresql database (Google Cloud SQL)
During initial set-up, one of the models was set up as follows:
class ExampleModel(models.Model):
id = models.CharField(max_length=60, unique=True, primary_key=True)
new_id = models.CharField(max_length=60, unique=True, null=True, db_index=True)
name = models.CharField(max_length=300, db_index=True)
tags = models.ManyToManyField(Tag, blank=True)
The id field contains a unique ID like: AB123456789.
I have since realised this is a mistake and would like to revert the primary key field to a standard auto-incrementing autofield, and instead use the 'new_id' field to store the unique ID.
Please can someone provide guidance on how I can make this change and perform the necessary database migrations? There are a number of foreign key fields in other models that currently use the id field in the above model which will need changing. As you can see in the above, there is also a many to many field between this model and a tag model.
I tried removing the id field from my models.py file and migrating - it initially gave an error linked to null fields and default values so I set a dummy default value in the Terminal window and removed this in the migration file.
The database removed the id field successfully and generated a new Autonumber primary key field however none of the many to many or foreign key relationships were kept post migration. I have since rolled back to a prior version of the database.
Generally this will be your approach. Steps 1-4 can be merged into a single deployment. Steps 5-7 into another. Then 8-9 would be the final.
Create new auto field.
Create new FK nullable relationships on models
Update all code that creates related models to populate both FK's
Populate all the null FK fields via a script
Make the new FK fields not-nullable
Make old FK's nullable.
Remove old FK usages from code base
Migration to remove old ID field and FKs.
(optional) Rename auto field to be ID and potentially use Django's built-in field.
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.
I'm looking to create a url to visit a user profile using a slug. Ie. I want to visit /profile/myname to bring up my user profile. What I am having difficulties with is implementing the slug field for a user model.
Additionally, not sure if this matters or not but I have created a UserProfile model which extends the standard User model as shown below:
from django.contrib.auth.models import User
from autoslug import AutoSlugField
class UserProfile(models.Model):
user = models.ForeignKey(User, related_name='profile_name')
about_me = models.TextField(null=True, blank=True)
slug = AutoSlugField(populate_from='User.username', default='', unique=True)
which gives the error (when trying to migrate):
DETAIL: Key (slug)=() is duplicated.
I believe the urls to be correct but have included it for reference (in an app named profile):
url(r'^(?P<slug>[\w-]+)', views.detail, name='detail')
It means you already have some records in userprofile table with empty/null values in slug field. Because you've marked that field as unique=True it can only have one field with empty value. To avoid this error, delete the records with empty value in slug field, or just assign them a unique slug and you'll be good to go.
And as you can understand from above, having default='' in a field that has unique=True wont work. Unique means unique, even '' as an empty value is considered a unique value and can be used in just one row if you have unique=True. That also means you cannot have any default value in a unique field.
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.