Django-allauth package creates a model SocialAccount, with a ForeignKey to User. I can't manage to prefetch this information in my queryset.
My model:
class Placerating(models.Model):
author = models.ForeignKey('auth.User', null=True, on_delete=models.SET_NULL)
Django-allauth model:
class SocialAccount(models.Model):
user = models.ForeignKey(allauth.app_settings.USER_MODEL, on_delete=models.CASCADE)
When I try to prefetch this data:
rating = Placerating.objects.all().prefetch_related('author__socialaccount')
I get the following error message:
AttributeError: Cannot find 'socialaccount' on User object, 'author__socialaccount' is an invalid parameter to prefetch_related()
Any clue ? Thanks!
I got my answer.
SocialAccount is a reverse Foreign key, so "_set" must be added at the end:
rating = Placerating.objects.all().prefetch_related('author__socialaccount_set')
Related
I have a queryset of users, which are instances of the model User.
A second model called Patient has a OneToOneField named user:
user = OneToOneField('users.User', on_delete=CASCADE, related_name="patient",
blank=True, null=True)
The goal is to get a queryset of all patients from the queryset of users.
I thought that by using the related_name would be enough, meaning:
queryset_of_users=User.objects.filter(main_group='patients')
queryset_of_patients=queryset_of_users.patient
but it seems this is not it since I get the following error:
AttributeError: 'QuerySet' object has no attribute 'patient'
Any ideas?
Found it,
It works by making a second query:
queryset_of_patients=Patient.objects.filter(user__in=queryset_of_users)
I have a UserProfile table which is in relation with the default Django User table. Here's how it looks.
class UserProfile(models.Model):
user = user.OneToOneField(User, on_delete=models.CASCADE)
section = models.CharField(max_length=255, blank=True)
year = models.IntegerField(null=True, blank=True)
course = models.CharField(max_length=255, blank=True)
qrcode = models.CharField(max_length=255, blank=True)
present = models.BooleanField(default=False)
I am trying to insert the data into the UserProfile table using the Django Shell.
from users.models import UserProfile
a = UserProfile(qrcode="hello")
a.save()
This is how I have always known to insert data into tables, it has always worked. BUT when i try to do this in UserProfile model. I get this exception. NOT NULL constraint failed: users_userprofile.user_id. Which in turn is caused by the following exception Error in formatting: RelatedObjectDoesNotExist: UserProfile has no user.
I somewhat understand that I somehow need to supply a user instance. But I am clueless as to how. Can someone please help me.
Firstly you need to create User.
u1 = User(username='user1')
u1.save()
Create a UserProfile. Pass the ID of the “parent” object as this object’s ID:
v1 = UserProfile(user=u1, ....)
v1.save()
refer this
You need to create your User first
user = User.objects.create(username='user')
and then you can do:
user_profile = UserProfile.objects.create(user=user, ...)
I am using django 2.0. For users I am using the model django.contrib.auth.models.User. I have stored a user with username john in it. I have a Post model which uses a User model as ForeignKey. This is my models.py:
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
post_content = models.CharField(max_length=140)
post_date = models.DateTimeField('post date')
post_user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.post_content
...In my views.py I am creating a post with:
from django.contrib.models import User
Post.objects.create(post_content=post_text, post_date=timezone.now(),post_user=User.objects.get(username='john'))
...In one part of the code. When I run I get this error:
FOREIGN KEY constraint failed
IntegrityError at /
And it points to the line in which I create the user in views.py.
Is there a proper way to ForeignKey a user model? Any guidance appreciated. Thank you :-).
EDIT:It works after doing a reset to the database because I made an error with migrations. Run you migrations properly friends!
I have 2 database tables, Prospects and Profile. They're related by a One-to-one foreign key relationship
Model.py
class Prospect(models.Model):
profile = models.OneToOneField(Profile, on_delete=models.CASCADE, null=True, blank=True, related_name="profile_prospects")
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
In my view.py
prospects = prospects[:50]
I have a QuerySet of prospects (prospects is working correctly, exactly what I want), and I would like to retrieve a QuerySet of profiles based on the database model above. I tried
profiles = Profile.objects.filter(profile_prospects__in = prospects)
It returns an error of
django.db.utils.ProgrammingError: subquery has too many columns
How can I get all the relevant profiles?
You have spaces in
profiles = Profile.objects.filter(profile_prospects__in = prospects)
Sorry, I might be confused here. But isn't the profile automatically inherited by the prospect since it's a one-to-one relationship?
When you have the prospect you should be able to get the profile like this
prospect.profile
Again, I might have gotten the question wrong.
I encountered a problem with Django 1.7. When I want make my migration I raise this exception :
Models aren't loaded yet.
I tried solution said here but it doesn't work.
I saw this solution but I can't how do it with my models.
Error is due to person_type field on UserProfile Class. When I removed it migrations works.
class Typo_model(BaseModel):
key = models.CharField(max_length=32, db_index=True)
text = models.CharField(max_length=255)
class UserProfile(AbstractUser, BaseModel):
person_type = models.ForeignKey(Typo_model, queryset =
Typo_model.objects.filter(cle="person_type"), verbose_name="Person type")
I don't think you can set queryset on a ForeignKey. Purhaps limit_choices_to is what you are looking for. https://docs.djangoproject.com/en/1.7/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to
Like this:
person_type = models.ForeignKey(
Typo_model,
limit_choices_to={'cle': 'person_type'}
)