I want to get all articles in which a user has commented but the article itself is created by others.
Here are the models:
class Article(models.Model):
title = models.CharField(max_length=300, blank=False)
body = models.TextField(max_length=10000, blank=False)
created = models.DateTimeField(auto_now_add=True)
creator = models.ForeignKey(User, blank=True, null=True)
updated = models.DateTimeField(auto_now=True)
class Comment(models.Model):
title = models.CharField(null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
creator = models.ForeignKey(User, null=True)
updated = models.DateTimeField(auto_now=True)
article = models.ForeignKey(Article)
body = models.TextField(max_length=10000)
published = models.BooleanField(default=True)
The query that I use is:
mycomments = Article.objects.filter(Q(comment__creator=request.user) and ~Q(creator=request.user)).order_by("-created")[:30]
But for some reason it returns many articles in which the user has not commented. So I'm wondering what should be the correct queryset?
Article.objects.filter(comment__creator=request.user) \
.exclude(creator=request.user).distinct()
Related
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.
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', )
I have built an application with comments that are commented on a parent comment. I have the following comment model. How can I associate the comment with a parent comment ?
class Comment(models.Model):
uuid = models.UUIDField(max_length=255, default = uuid.uuid4)
description = models.CharField(max_length=5000, default="")
likes = models.PositiveIntegerField(default=0)
dislikes = models.PositiveIntegerField(default=0)
uploaded_at = models.DateTimeField(null=True, blank=True)
commentinguser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
video = models.ForeignKey(Video, on_delete=models.CASCADE)
You can have a recursive ForeignKey (a foreign key to the same model) by passing "self"
parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True)
I have three models : Domain Topic Post
Topic has a foreign key to Domain and Post has a foreign key to Topic.
Post has a field updated_on.
I want to annotate last_updated field in Domain queryset which would contain the latest post object from Post .
Edit 1: Added models definition:
class Board(models.Model):
name = models.CharField(max_length=30, unique=True)
description = models.CharField(max_length=50)
creation_time = models.DateTimeField(auto_now_add=True)
class Topic(models.Model):
subject = models.CharField(max_length=300, unique=True)
board = models.ForeignKey(Board, on_delete=models.SET_NULL, related_name='topics', null=True)
created_by = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='topics', null=True)
created_on = models.DateTimeField(auto_now_add=True)
views = models.PositiveIntegerField(default=0)
class Post(models.Model):
message = models.CharField(max_length=5000)
created_by = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='posts', null=True)
created_on = models.DateTimeField(auto_now_add=True)
topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, related_name='posts', null=True)
updated_on = models.DateTimeField(default=timezone.now)
users on my project can subscribe model Board and I try to show all objects from all subscribed boards who user subscribe.
But don't know how. I search through internet but nothing help me in this.
Model board:
class Board(models.Model):
title = models.CharField(max_length=255, verbose_name='Tytuł')
slug = AutoSlugField(populate_from='title', unique=True)
image = ImageField(blank=True, manual_crop="" ,verbose_name='Tło')
body = models.TextField(verbose_name='Opis kategorii')
author = models.ForeignKey(User, on_delete=models.CASCADE)
subscribers = models.ManyToManyField(User, related_name='subscribed_boards', blank=True)
created_at = models.DateTimeField(auto_now_add=True)
Models related to(I try to show this objects from subscribed boards):
class Subject(models.Model):
title = models.CharField(max_length=255, verbose_name='Tytuł')
slug = AutoSlugField(populate_from='title', unique=True)
body = HTMLField(blank=True, verbose_name='Treść')
image = models.ImageField(upload_to='subject', null=True, blank=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
board = models.ForeignKey(Board, on_delete=models.CASCADE, related_name='subjects', verbose_name='Kategoria')
votes = GenericRelation(LikeDislike, related_query_name='subjectsvotes')
class Embed(models.Model):
url = models.URLField(max_length=255)
title = models.CharField(max_length=255, verbose_name='Tytuł')
description = HTMLField(verbose_name='Opis')
thumbnail_url = models.URLField(max_length=255)
html = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
board = models.ForeignKey(Board, on_delete=models.CASCADE, blank=True, null=True, related_name='embeds', verbose_name='Kategoria')
votes = GenericRelation(LikeDislike, related_query_name='embedvotes')
slug = AutoSlugField(populate_from='title', unique=True)
In view I try this:
def feed(request):
user = get_object_or_404(User, username=request.user)
feed = user.subscribed_boards.all()
embeds = feed.filter(embed__in=feed)
return render(request, 'boards/feed.html',
{'feed': feed,
'embeds': embeds})
You have a circular reference from feed to feed in you current code. The actually required code is a lot simpler:
boards = user.subscribed_boards.prefetch_related('embeds')
You can now loop over the boards and the embeds in the boards:
for board in boards:
print(board.title)
for embed in board.embeds.all():
print(embed.title)
The above is Python code to show how to access the objects; you would more likely want to do the loops in the template.
You can try the below code:
def feed(request):
user = get_object_or_404(User, username=request.user)
feed = user.subscribed_boards.all()
embeds = user.subscribed_boards.filter(embed__in=feed)
return render(request, 'boards/feed.html',
{'feed': feed,
'embeds': embeds})
Please check if it works.