Django models: database design for user and follower - django

In Django model I am making a table 'followers', which has:
user's id. (this is followed by)
user's id (this is follower)
that's simple a user can follow other users.
How should I define the model in Django?
I tried this, but does not work:
user = models.ForeignKey('self')
follower_id = models.ForeignKey('self')
How should this be done?
thanks

The 'self' argument won't work unless you have a model called self.
Assuming that your assignment model is called Following, and you're using the built in User model then you can do:
class Following(models.Model):
target = models.ForeignKey('User', related_name='followers')
follower = models.ForeignKey('User', related_name='targets')
This will likely need some further uniqueness and validation logic.
Note the related_name attribute, see https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ForeignKey.related_name. This means that for a given user object you can do user.targets.all() to get users they follow, and user.followers.all() to get users who follow them.
Note also that Django returns target model instances, not IDs, in the ORM. This means that even though the underlying table may be called follower_id, in the python code following.follower will return an actual User object.

Seeing as Following is actually the through table for the many-to-many relationship between Users. I would create a Profile model which extends the Django User model, and then declare the many-to-many relationship (using ManyToManyField).
from django.contrib.auth.models import User
from django.db import models
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
following = models.ManyToManyField(User, related_name='followers')

Use the many to many field.
followers = models.ManyToManyField('self', symmetrical=False)

Related

Django application doesn't seem to recognize related name?

I have a django app with a User's model that contains a followers field that serves the purpose of containing who follows the user and by using related_name we can get who the User follows. Vice versa type of thing. Printing the User's followers works, but I can't seem to get the followees to work.
views.py
followers = User.objects.get(username='bellfrank2').followers.all()
following = User.objects.get(username='bellfrank2').followees.all()
print(followers)
print(following)
models.py
class User(AbstractUser):
followers = models.ManyToManyField('self', blank=True, related_name="followees")
Error:
AttributeError: 'User' object has no attribute 'followees'
According to documentation all many to many relationships that are recursive are also symmetrical by default.
See here: https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.ManyToManyField.symmetrical
When Django processes this model, it identifies that it has a ManyToManyField on itself, and as a result, it doesn’t add a person_set attribute to the Person class. Instead, the ManyToManyField is assumed to be symmetrical – that is, if I am your friend, then you are my friend.
So to, make your field actually create the followees attribute you need to set the symmetrical attribute to False.
models.py
class User(AbstractUser):
followers = models.ManyToManyField('self', blank=True, related_name="followees", symmetrical=False)

Filter django query set based on whether a foreign key relationship exists

So I have two models.
class Post(models.Model):
id = models.OidField('object id', unique=True)
class ArchivedFlag(models.Model):
post = models.ForeignKey(post,
on_delete=models.CASCADE,
related_name='archived_flag')
user = models.ForeignKey(User,
on_delete=models.CASCADE,
related_name='archives')
In views.py I have generated a list of all posts by some criteria, 'plist'.
I want to filter the list based on posts that DO NOT have an ArchivedFlag object relationship. Basically the ArchivedFlag model is a tool hide certain posts.
How can I do this? I'm trying to do something along the lines of
plist = plist.exclude(models.ForeignKey.Post exists)
but I'm unsure of the exact syntax.
You can exclude Post objects for which anArchivedFlag exists with:
Post.objects.exclude(archived_flag__isnull=False)
or easier with a simple filter:
Post.objects.filter(archived_flag=None)
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

How can I link model in new app with specific model data in allauth?

In Django, I have installed allauth. Then I have created a new app, where user's actions will be. I want to link each of the actions with allauth's user data within EmailAddress model.
My questions are:
Normally, data is defined by user_action = models.CharField(max_length=200) and such. ForeignKey on user action does not allow defining field types, at least from what I've seen. How can I define it, or is it okay not to define it?
How can I define the relationship with data in allauth's model that's not anywhere near this new app? For example, I have:
from django.db import models
import allauth.account.models
class Button(models.Model):
button_one = models.ForeignKey('EmailAddress', on_delete=models.CASCADE)
def __str__(self):
return self.button_one
It does not work. The error shows:
input.Button.comment: (fields.E300) Field defines a relation with model 'EmailAddress', which is either not installed, or is abstract.
input.Button.comment: (fields.E307) The field input.Button.comment was declared with a lazy reference to 'input.emailaddress', but app 'input' doesn't provide model 'emailaddress'.
The allauth model data ("user") in question is:
class EmailAddress(models.Model):
user = models.ForeignKey(allauth_app_settings.USER_MODEL,
verbose_name=_('user'),
on_delete=models.CASCADE)
email = models.EmailField(unique=app_settings.UNIQUE_EMAIL,
max_length=app_settings.EMAIL_MAX_LENGTH,
verbose_name=_('e-mail address'))
verified = models.BooleanField(verbose_name=_('verified'), default=False)
primary = models.BooleanField(verbose_name=_('primary'), default=False)
objects = EmailAddressManager()
I'm using virtualenv and have allauth installed within the project.
So EmailAddress is your User model?
In that case you might be able to do this via the standard way by referring to settings.py
Import . from settings
class Button(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)

django admin Model edit form - How to filter foreignkeys to only related models

I have an account model in django which has a foreignkey to Payment and a onetoone to Address.
In the Account section in the admin, I can edit a specific model and edit the fields payment and address via a select widget. However how can I filter the options so that it only shows related models. (ie not every address or payment from every user, only the ones from that user).
The RelatedOnlyFieldListFilter seems to only apply to the model list view. Is there a way to use this in the model edit view?
What you are probably looking for is call inlines. It allows you to edit related object directly in the parent model form which in this case would be the Account model. Here is an example of implementation:
class Account(models.Model):
name = models.CharField(max_length=100)
class Payment(models.Model):
account= models.ForeignKey(Account, on_delete=models.CASCADE)
amount= models.CharField(max_length=100)
class Adress(models.Model):
account= models.OneToOneField(Account, on_delete=models.CASCADE)
adress= models.CharField(max_length=100):
class AccountAdmin(admin.ModelAdmin):
inlines = [
Paymentinline,
Adressinline,
]
Note that this is not a complete implementation (you will need to construct both inlines), follow the documentation on inlines for further information but above are the basics to it.

Django - Multiple User Profiles

Initially, I started my UserProfile like this:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
verified = models.BooleanField()
mobile = models.CharField(max_length=32)
def __unicode__(self):
return self.user.email
Which works nicely along with AUTH_PROFILE_MODULE = 'accounts.UserProfile' set in settings.py.
However, I have two different kinds of users in my website, Individuals and Corporate, each having their own unique attributes. For instance, I would want my Individual users to have a single user only, hence having user = models.OneToOneField(User), and for Corporate I would want them to have multiple users related to the same profile, so I would have user = models.ForeignKey(User) instead.
So I thought about segregating the model into two different models, IndivProfile and CorpProfile, both inheriting from UserProfile while moving the model-specific attributes into the relevant sub-models. Seems like a good idea to me and would probably work, however I would not be able to specify AUTH_PROFILE_MODULE this way since I'm having two user profiles that would be different for different users.
I also thought about doing it the other way around, having UserProfile inherit from multiple classes (models), something like this:
class UserProfile(IndivProfile, CorpProfile):
# some field
def __unicode__(self):
return self.user.email
This way I would set AUTH_PROFILE_MODULE = 'accounts.UserProfile' and solve its problem. But that doesn't look like it's going to work, since inheritance in python works from left to right and all the variables in IndivProfile will be dominant.
Sure I can always have one single model with IndivProfile and CorpProfile variables all mixed in together and then I would use the required ones where necessary. But that is just doesn't look clean to me, I would rather have them segregated and use the appropriate model in the appropriate place.
Any suggestions of a clean way of doing this?
You can do this in following way. Have a profile which will contains common fields which are necessary in both profiles. And you have already done this by creating class UserProfile.
class UserProfile(models.Model):
user = models.ForeignKey(User)
# Some common fields here, which are shared among both corporate and individual profiles
class CorporateUser(models.Model):
profile = models.ForeignKey(UserProfile)
# Corporate fields here
class Meta:
db_table = 'corporate_user'
class IndividualUser(models.Model):
profile = models.ForeignKey(UserProfile)
# Individual user fields here
class Meta:
db_table = 'individual_user'
There is no rocket science involved here. Just have a keyword which will distinguish between corporate profile or individual profile. E.g. Consider that the user is signing up. Then have a field on form which will differentiate whether the user is signing up for corporate or not. And Use that keyword(request parameter) to save the user in respective model.
Then later on when ever you want to check that the profile of user is corporate or individual you can check it by writing a small function.
def is_corporate_profile(profile):
try:
profile.corporate_user
return True
except CorporateUser.DoesNotExist:
return False
# If there is no corporate profile is associated with main profile then it will raise `DoesNotExist` exception and it means its individual profile
# You can use this function as a template function also to use in template
{% if profile|is_corporate_profile %}
Hope this will lead you some where. Thanks!
I have done it this way.
PROFILE_TYPES = (
(u'INDV', 'Individual'),
(u'CORP', 'Corporate'),
)
# used just to define the relation between User and Profile
class UserProfile(models.Model):
user = models.ForeignKey(User)
profile = models.ForeignKey('Profile')
type = models.CharField(choices=PROFILE_TYPES, max_length=16)
# common fields reside here
class Profile(models.Model):
verified = models.BooleanField(default=False)
I ended up using an intermediate table to reflect the relation between two abstract models, User which is already defined in Django, and my Profile model. In case of having attributes that are not common, I will create a new model and relate it to Profile.
Could be worth to try using a through field. The idea behind it is to use the UserProfile model as through model for the CorpProfile or IndivProfile models. That way it is being created as soon as a Corp or Indiv Profile is linked to a user:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.ForeignKey(User)
profile = models.ForeignKey(Profile, related_name='special_profile')
class Profile(models.Model):
common_property=something
class CorpProfile(Profile):
user=models.ForeignKey(User, through=UserProfile)
corp_property1=someproperty1
corp_property2=someproperty2
class IndivProfile(Profile):
user=models.ForeignKey(User, through=UserProfile, unique=true)
indiv_property1=something
indiv_property2=something
I think that way it should be possible to set AUTH_PROFILE_MODULE = 'accounts.UserProfile', and every time you create either a CorpProfile or a IndivProfile that is linked to a real user a unique UserProfile model is created. You can then access that with db queries or whatever you want.
I haven't tested this, so no guarantees. It may be a little bit hacky, but on the other side i find the idea quite appealing. :)