Django filter intermediary table & social media - django

So i'm practicing django with a social media website(just for practice). I'm trying to do a filter in my view to get all of the "Beats" from users i'm friends with. Im using an intermediary table for "relationships". I'm currently getting my Beat Stream by using:
my_stream = Beat.objects.filter(artist=user)
But i'm trying to get only the beats of the people i'm "related_to" in the relationships model.
MODELS:
class Beat(models.Model):
created_at = models.DateTimeField( default=datetime.now)
title = models.CharField(max_length=255)
description = models.TextField(blank=True, null=True)
likes = models.IntegerField(default=0)
artist = models.ForeignKey(User, null=True, blank=True)
beat_cover = models.ImageField(null=True, blank=True);
admin_name = models.CharField(max_length=255, blank=True, null=True)
class Meta:
ordering = ['-created_at']
def __unicode__(self):
return unicode(self.admin_name)
class UserProfile(models.Model):
user = models.OneToOneField(User)
admin_name = models.CharField(default="beat",max_length=255,blank=True, null=True)
def __unicode__(self):
return unicode(self.admin_name)
class Relationship(models.Model):
from_user = models.ForeignKey(User, related_name="relationships")
to_user = models.ForeignKey(User, related_name="related_to")
class Meta:
index_together = ['from_user','to_user']

You should do:
related_users = Relationship.objects.filter(from_user=user) \
.values_list('to_user', flat=True).distinct()
my_stream = Beat.objects.filter(artist__in=related_users)

Related

How to use django-autocomplete-light and django-hacker to make a chained dropdown in django admin?

I have 3 models 1) university 2) courses and 3) enquiry.
My enquiry model has a foreign key to "course". And Course has a foreign key to the university. I only want to show the courses related to that university while adding an enquiry. I tried django-smart-select but failed to do so. I tried This answer but I dont understand the logic and failed to implement in my project.
this is my models.py file
class university(models.Model):
univ_name = models.CharField(max_length=100)
country = CountryField(blank=True, null=True)
univ_desc = models.CharField(max_length=1000)
univ_logo = models.ImageField(upload_to="media")
univ_phone = models.CharField(max_length=10, blank=True)
univ_email = models.EmailField(max_length=254, blank=True)
univ_website = models.URLField(blank=True)
assigned_users = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, default="")
def __str__(self):
return self.univ_name
class Meta:
verbose_name_plural = "Universities"
class Course(models.Model):
university = models.ForeignKey(university, on_delete=models.CASCADE)
course_name = models.CharField(max_length=100)
course_levels = models.ForeignKey(course_levels, on_delete=models.CASCADE)
intake = models.ForeignKey(intake, on_delete=models.CASCADE)
documents_required = models.ForeignKey(documents_required, on_delete=models.CASCADE)
course_requirements = models.ForeignKey(course_requirements, on_delete=models.CASCADE)
Active = models.BooleanField()
def __str__(self):
return self.course_name
class enquiry(models.Model):
student_name = models.CharField(max_length=100)
student_phone = models.CharField(max_length=10)
student_email = models.EmailField()
student_address = models.TextField()
current_education = models.ForeignKey(current_education, on_delete=models.CASCADE)
country_interested = CountryField(blank=True, null=True)
university_interested = models.ForeignKey(university, on_delete=models.CASCADE)
course_interested = models.ForeignKey(Course, on_delete=models.CASCADE, limit_choices_to={'Active':True})
level_applying_for = models.ForeignKey(course_levels, on_delete=models.CASCADE)
intake_interested = models.ForeignKey(intake, on_delete=models.CASCADE)
assigned_users = models.ForeignKey(User, on_delete=models.CASCADE, default="", limit_choices_to={"is_active": True})
enquiry_status = models.ForeignKey(enquiry_status, on_delete=models.CASCADE, default="")
course_interested= ChainedForeignKey(Course,chained_field= 'university_interested',chained_model_field= 'university',show_all= False,auto_choose= True,sort=True,limit_choices_to = {"Active": True},)
I want to show the course_interested field related to that university. Need help.
I tried using django-smart-select but failed to implement it. I am not aware of jquery and ajax so that is out of the question to use in my project.
got the solution I used the django-select2 and was able to solve this issue.

Django rest framework get data from foreign key relation?

I have a models like this:
class Author(models.Model):
name = models.CharField(max_length=150, blank=False, null=False)
dob = models.DateField(null=True, blank=True)
description = models.TextField(max_length=2000, blank=False, default="This author doesn't have any description yet!")
image = models.ImageField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created']
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=200, blank=False, null=False)
author = models.CharField(max_length=200)
genres = models.ManyToManyField(Genre, related_name='genre', blank=True)
author = models.ForeignKey(Author, related_name='author', blank=True, on_delete=models.CASCADE)
description = models.TextField(max_length=1200, blank=False, default="This book doesn't have description yet!")
image = models.ImageField(default="")
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created']
def __str__(self):
return self.title
class Review(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
book = models.ForeignKey(Book, on_delete=models.CASCADE)
title = models.CharField(max_length=100, null=False, blank=False, help_text="Title overall of your review")
rating = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(5)], help_text='Rating in range 0-5')
description = models.TextField(max_length=1000, null=False, blank=False)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
I want to get Book data response in json with my reviews of the book from my Review table but don't know how. I am not getting any useful solution from documentation and Google, please help.
You could set the related_name field in the book field of the Review model.
class Review(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name = 'reviews')
...
Then in the serializer, you can add the related field.
class ReviewSerializer(serializers.ModelSerializer):
class Meta:
model = Review
fields = '__all__'
class BookSerializer(serializers.ModelSerializer):
reviews = ReviewSerializer(many = True)
class Meta:
model = Book
fields = '__all__'
extra_fields = ('reviews', )

How do I show only a subset of options in a Django dropdown menu

I have an app that allows users to signup and register for courses (from a 'TrainingInstance' model). These events have names etc and are categorised as Past or Current in the database (in the 'Training' model). When I show the BuildOrderForm in my template, I want only options for Current trainings to be shown in the dropdown menu. How can this be done in Django without javascript or Ajax?
I have the following form in forms.py:
class BuildOrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['training_registered']
And the following models in models.py:
class Training(models.Model):
""" Model which specifies the training category (name) and whether they are Past or Present"""
YEAR = (
('current', 'current'),
('past', 'past'),
)
name = models.CharField(max_length=200, null=True)
year= models.CharField(max_length=200, null=True, choices=YEAR, default='current')
def __str__(self):
return self.name
class TrainingInstance(models.Model):
""" Creates a model of different instances of each training ( May 2021 etc) """
name = models.CharField(max_length=200, null=True, blank=True)
venue = models.CharField(max_length=200, null=True, blank=True)
training = models.ForeignKey(Training, on_delete= models.CASCADE, null = True)
training_month = models.CharField(max_length=200, null=True, blank=True)
participant_date = models.CharField(max_length=20, null=True, blank=True)
staff_date = models.CharField(max_length=20, null=True, blank=True)
graduation_date = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return self.name
class Order(models.Model):
REGSTATUS = (
('registered', 'registered'),
('enrolled', 'enrolled'),
('holding', 'holding'),
('withdrawn', 'withdrawn'),
('waiting', 'waiting'),
)
customer = models.ForeignKey(Customer, on_delete= models.CASCADE, null = True)
training_registered = models.ForeignKey(TrainingInstance, on_delete= models.SET_NULL, blank = True, null = True)
registration_date = models.DateTimeField(null=True,blank=True)
regstatus = models.CharField(max_length=200, null=True, choices=REGSTATUS, default='registered')
def __str__(self):
return self.customer.username
Here is what I have done - which works but I'm also open to feedback about good/bad practice.
class BuildOrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['training_registered']
def __init__(self,*args,**kwargs):
super (BuildOrderForm,self ).__init__(*args,**kwargs)
self.fields['training_registered'].queryset = TrainingInstance.objects.filter(training__year ="current")

Getting items related to selected foreign key in django

I'm building a django app that has customers model and projects model and tasks model. in tasks model I can select the customer name and project but the problem is that in admin panel it shows all the projects, is there any way to show projects only for the selected customer
from django.db import models
from django.contrib.auth.models import User
from suppliers.models import Currency
from users.models import Profile
class Customer(models.Model):
customer_id = models.AutoField(primary_key=True)
customer_first_name = models.CharField(max_length=200)
customer_last_name = models.CharField(max_length=200)
company = models.CharField(max_length=200)
customer_phone = models.CharField(max_length=200)
customer_address = models.CharField(max_length=200)
email = models.EmailField(null=True, blank=True)
website = models.CharField(max_length=200, null=True, blank=True)
creation_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
notes = models.TextField()
def __str__(self):
return str(self.customer_first_name) + ' ' + str(self.customer_last_name)
class Account(models.Model):
max_discount = models.DecimalField(max_digits=2, decimal_places=2)
credit_limit = models.DecimalField(max_digits=20, decimal_places=2)
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True)
currency = models.ForeignKey(Currency, on_delete=models.CASCADE)
sales_man = models.OneToOneField(User, on_delete=models.CASCADE)
Agent = models.OneToOneField(Profile, on_delete=models.CASCADE)
status = models.BooleanField(default=True)
reason = models.TextField()
class TaskPriority(models.Model):
priority_id = models.AutoField(primary_key=True)
task_priority_name = models.CharField(max_length=200)
def __str__(self):
return str(self.task_priority_name)
class Project(models.Model):
project_id = models.AutoField(primary_key=True)
project_name = models.CharField(max_length=200)
project_balance = models.DecimalField(max_digits=20, decimal_places=2)
customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE)
creation_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
notes = models.TextField()
def __str__(self):
return str(self.project_name)
class Task(models.Model):
task_id = models.AutoField(primary_key=True)
task_name = models.CharField(max_length=200)
customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE, blank=True, null=True)
task_priority = models.ForeignKey(TaskPriority, on_delete=models.CASCADE)
employee = models.ForeignKey(Profile, on_delete=models.CASCADE)
creation_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
project = models.ForeignKey(Project, null=True, blank=True, on_delete=models.CASCADE)
file_name = models.FileField(upload_to='projects_files')
notes = models.TextField()
def __str__(self):
return str(self.task_name)
You can use TabularInline to create project tab on customer record view in admin panel.
For example:
class ProjectInline(admin.TabularInline):
model = Project
extra = 1
verbose_name = 'Project'
verbose_name_plural = 'Projects'
list_display = ...
And in Customer Admin model add
class CustomerAdmin(admin.ModelAdmin):
...
inlines = (ProjectInline, )

DRF need values instead of ID

This is my serializer class
class ProjectSerializer(ModelSerializer):
class Meta:
model = Project
exclude = ['deleted_at']
This is Models.py
class MandatoryFields(SoftDeletionModel):
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="%(app_label)s_%(class)s_created",null=True)
updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="%(app_label)s_%(class)s_updated",null=True)
created_date = models.DateTimeField(auto_now_add=True,null=True)
modified_date = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Project(MandatoryFields, Model):
project_name = models.CharField(max_length=255, blank=True)
project_areas = models.CharField(max_length=255, blank=True)
project_manager = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True,
related_name="%(app_label)s_%(class)s_project_manager")
start_date = models.DateField(null=True, blank=True)
end_date = models.DateField(null=True, blank=True)
REQUIRED_FIELDS = []
def __str__(self):
return self.project_name
I am getting Id's for the foreign keys created_by,updated_by,project_manager .But I need the values instead of Id.
for example I am getting
created_by : 1
But I need
created_by: Alex
I have tried the following
class ProjectSerializer(ModelSerializer):
created_by = SlugRelatedField(read_only=True, slug_field='created_by')
class Meta:
model = Project
exclude = ['deleted_at']
But I am getting null values.
I think that's achievable by specifying source attribute for serializer field
Somthing like this:
class ProjectSerializer(ModelSerializer):
created_by = CharField(source="created_by.first_name")
class Meta:
model = Project
exclude = ['deleted_at']
Reference : https://www.django-rest-framework.org/api-guide/fields/#source