Get all objects defined by a Django ManyToManyField relationship - django

The site I'm building allows users to create "posts" and has a Twitter-like concept of followed users. For a given user, I'd like to show all of the posts from the users that they follow.
Here are my simplified models:
class User
# a standard django.contrib.auth user model
class UserProfile(models.Model):
# my AUTH_PROFILE_MODULE for django-profiles
user = models.ForeignKey(User, unique=True)
following = models.ManyToManyField('self', symmetrical=False, related_name="followed_by")
class Posts(models.Model):
user = models.ForeignKey(User)
post = models.TextField()
Question: How do you create a queryset of all Post objects from the Users that a given User is following?
I think I've made it more complicated by creating the "follow" relationship on UserProfile, which is not the model with the ForeignKey relationship with Posts.
UPDATE! Here's the answer:
Posts.objects.filter(user__userprofile__in=UserProfile.objects.get(user=your_user_object).following.all())

Posts.objects.filter(user__in=UserProfile.objects.get(user=your_user_object).following)

Related

Django subscriber feature

I am creating a django site/platform where the main concept is users can create shops and other users can subscribe to those who have shops open (think Etsy). Trying to implement the subscriber feature and this is a model I have so far for it:
class Subscriber(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
sub_shop = models.ForeignKey(Shop, on_delete=models.CASCADE)
It works perfect for giving users the ability to subscribe and have the subscribtions listed in their profile and vice versa for shop owners, but for now a user can subscribe to a shop as many times as they want and I would like to prevent this. Idk if there is a constraint to allow multiple subscriber model instances by the same user but not allow for the same exact 'user' and 'sub_shop' instance OR if I am just going on about this in a very bad way!
You can use a UniqueConstraint [Django-doc] to specify that the combination of user and sub_shop should be unique:
class Subscriber(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
sub_shop = models.ForeignKey(Shop, on_delete=models.CASCADE)
class Meta:
constraints = [
models.UniqueConstraint(
fields=['user', 'sub_shop'],
name='subscribe_once'
)
]
prior to django-2.2, you can work with unique_together [Django-doc]:
# prior to Django-2.2
class Subscriber(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
sub_shop = models.ForeignKey(Shop, on_delete=models.CASCADE)
class Meta:
unique_together = [['user', 'sub_shop']]
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.

Additional fields in Wagtail User Edit

I have extended my user model with the OneToOne model and would now like to be able to change additional information via the Wagtail user editing interface.
Customers App
#customer.model
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='customers')
org_title = models.CharField(max_length=500, default='', blank=True)
I have already seen this topic in wagtail docs: https://docs.wagtail.io/en/v2.9.3/advanced_topics/customisation/custom_user_models.html
But AbstractUser models are used. How can this be achieved with related models through the OneToOne relationship?

Setting a Django ForeignKey to multiple models

I have a simple model called WebProfile that stores a webpage URL and its title. This model has a ForeignKey to a Student model, which allows me to store the student's bookmarks.
I would like to reuse this model to also store bookmarks saved by teachers. What is the best way to have the owner ForeignKey point to either a Student or Teacher?
Note: in my actual use case, the target model classes are conceptually very different and do not share any common fields other than the WebProfile links.
class Student(models.Model):
...
class Teacher(models.Model):
...
class WebProfile(models.Model):
title = models.CharField(max_length=50)
link = models.URLField()
owner = models.ForeignKey('Student', on_delete=models.CASCADE, related_name="bookmarks")
If Teacher and Student are related to the User model you could change the ForeignKey in WebProfile to be related to the User model instead.
From there you can then workout when you get a WebProfile object whether the user is a Student or Teacher.
I was able to solve the problem by using Generic Relations as described in Django documentation
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class WebProfile(models.Model):
title = models.CharField(max_length=50)
link = models.URLField()
owner_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
owner_id = models.PositiveIntegerField()
owner = GenericForeignKey('owner_type', 'owner_id')

Many-To-Many Fields View on Django Admin

Basically I am trying to recreate a fields in this model that is similar to django user authenticate system, for this I try using many-to-many fields but it ended up like this.
I am trying to have another field that can show what exist and another field for I have chosen similar to django admin, which looks like this.
This is my code
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
class BlogPage(models.Model):
category = models.ManyToManyField(Category)
title = models.CharField(max_length=128)
preview = models.TextField(max_length=256)
content = models.TextField()
I believe what you want is a filter_horizontal widget used in the Admin template. This should help: Django Admin ManyToManyField
currently i am able to display many to many fields is admin panel
models.py
class Abc(models.Model):
course = models.ManyToManyField(Course, blank=True)
admin.py
class AbcsAdmin(admin.ModelAdmin):
"""
Admin panel management for Alumni
"""
list_display = ["id","get_course"]
def get_course(self,obj):
return [course.name for course in obj.course.all()]

Django ManyToManyField relationship

I have the following Django model:
class opetest(models.Model):
name = models.CharField(max_length=200)
people = models.ManyToManyField(User, blank=True)
This m2m relationship is available on User object as 'opetest_set'.
How can I make available to edit this m2m relationship in django admin 'User edit page'?
To edit m2m in Django admin use InlineModelAdmin. In order to use your own UserAdmin you should unregister User first, like this:
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
To make opetest accessible from User instance:
class opetest(models.Model):
name = models.CharField(max_length=200)
people = models.ManyToManyField(User, blank=True, related_name='opetests')
Then user.opetests.all()