django queryset filter foreignkey - django

I'm having problems trying to use the queryset filter with my models.
It is a control for posts in groups.
This is my code:
class Post(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
class Group(models.Model):
title = models.CharField(max_length=200)
url = models.URLField(unique=True)
class Control(models.Model):
published = models.DateField(auto_now=False, auto_now_add=False)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
I'm trying to get all posts from a group with the title "title":
queryset_list = Control.objects.filter(group__control="title")
My models might nit be right, I'm new to this.
Any help?

Maybe it typo error?
queryset_list = Control.objects.filter(group__title="title")
# ^^^^^^
posts_title = queryset_list.values('post__title')

First, you should add a ManyToManyField on Group (docs):
class Group(models.Model):
title = models.CharField(max_length=200)
url = models.URLField(unique=True)
posts = models.ManyToManyField('Post', through='Control')
The other two models remain the same, but now you can easily grab posts for a Group:
posts = Group.objects.get(title='some title').posts.all()

Related

Query M2M relations in Django

I've the following model:
class Quiz(models.Model):
name = models.CharField(max_length=255)
month = models.DateField()
class Question(models.Model):
title = models.CharField(max_lenght=255)
category = models.CharField(max_length=255)
status = models.CharField(max_length=255, status=(('Pending', 'Pending'), ('Approved', 'Approved'))
class Contest(models.Model):
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
questions = models.ManyToManyField(Question, related_name='contest_questions')
Now I want to get list of quizes with all questions whose status=Pending?
Any help would be much appreciated!
Another approach is query directly from the M2M table using values_list():
quiz_ids = list(Contest.objects.filter(questions__status='Pending').values_list('quiz__id', flat=True))
quiz_query = Quiz.objects.filter(id__in=quiz_ids)

How to use model functions in Views for multiple instances in Django?

I have a Blog Post Model and I have defined a function to calculate the no of likes.
The Model is as follows ->
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.PROTECT)
title = models.CharField(max_length=255)
description = models.CharField(max_length=1000,null=True)
Tags = models.CharField(max_length = 255,null=True,blank=True)
Created_date = models.DateTimeField(auto_now_add=True)
Updated_date = models.DateTimeField(auto_now=True)
category = models.ForeignKey(Category, on_delete=models.PROTECT)
Likes = models.ManyToManyField(to=User, related_name='Post_likes')
def __str__(self):
return self.title
def likesCount(self):
return self.Likes.count()
Now I am querying the Post Model from the DB to get all the Posts as follows ->
posts = Post.objects.select_related().prefetch_related('images_set','comments_post').annotate(Count('comments_post')).all()
Here when I loop over the posts I can call the likesCount function and it gives me the correct result as well but I want to return the No of likes to the template.
How can I do that?
in your template, try this:
{{ post.likes_set.count }}
and please make the field names lowercase, they are not Classes

Django admin says SuspiciousOperation, filtering not allowed

I have 3 related models in my system. Each user belongs to a particular place. Users can send messages, and comment on messages, kind of like forum threads.
Here are the 3 models:
class Place(models.Model):
name = models.CharField(max_length=50, unique=True)
slug = models.SlugField(max_length=50, unique=True)
class Message(models.Model):
creator = models.ForeignKey(User)
title = models.CharField(max_length=40)
content = models.CharField(max_length=3000)
date_created = models.DateTimeField(default=timezone.now)
place = models.ForeignKey(Place)
class Comment(models.Model):
creator = models.ForeignKey(User)
content = models.CharField(max_length=3000)
date_created = models.DateTimeField(default=timezone.now)
message = models.ForeignKey(Message)
I want this structure to be reflected in my AdminModels. So for my PlaceAdmin I wrote this:
class PlaceAdmin(admin.ModelAdmin):
list_display = ('name', 'slug', 'list_messages')
def list_messages(self, obj):
url = reverse('admin:user_content_message_changelist')
return 'List messages'.format(url, obj.id)
list_messages.allow_tags = True
list_messages.short_description = 'Messages'
This works perfectly, each place links to a list of messages filtered by that place. So I did the same for my MessageAdmin:
class MessageAdmin(admin.ModelAdmin):
list_display = ('title', 'list_comments')
def list_comments(self, obj):
url = reverse('admin:user_content_comment_changelist')
return 'List comments'.format(url, obj.id)
list_comments.allow_tags = True
list_comments.short_description = 'Comments'
And I get the following error:
SuspiciousOperation at /admin/user_content/comment/
Filtering by message__id__exact not allowed
I don't understand why one is allowed and the other isn't. Any ideas? I'm using Django 1.5.
I realised I made a mistake - the code I showed here was simplified, and the Message model actually inherits from an abstract Content model, so I needed the URL for the comment list to be:
List comments

Django Many to Many Relationship backward querying

I have 2 models named 'Author' and 'Entry' as defined below.
class Author(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField()
msgtoauthor = models.TextField()
class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateTimeField()
authors = models.ManyToManyField(Author)
I am trying to access 'Author.msgtoauthor' from 'Entry'.
I know, I can retrieve the relationship between Entry and Author by
e = Entry.objects.get(authors)
Is it possible to extract the author id?
I know in the backend, Django creates a table for Authors and Entries but I want to update 'msgtoauthors' from a method in 'Entry'.
Thanks In Advance.
Did you mean
for author in my_entry.authors.all():
author.msgtoauth = 'Here is new content'
author.save()
?
Entry.authors returns a RelatedManager and my_entry.authors.all() is a QuerySet, that returns the Author objects. See https://docs.djangoproject.com/en/1.3/ref/models/relations/ and https://docs.djangoproject.com/en/1.3/topics/db/models/#many-to-many-relationships.
(Updated.)
Try this:
class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateTimeField()
authors = models.ManyToManyField(Author)
def msgtoat(self, message):
self.authors.update(msgtoauthor=message)
For example, to update an entry:
entry.msgtoat('Hello')
If all the authors get the same value you can do:
entry.authors.update(msgtoauthor='Hey there!')
https://github.com/Ry10p/django-Plugis/blob/master/courses/models.py
line 52
class name():
the_thing1 = models.CharField()
another = models.TextField()
class name2():
the_thing2 = models.ForignKey(the_thing1)
another2 = models.ForignKey(another)
-Cheers

Searching in several tables with django-haystack

I've got the Restaurant and Comment models shown below. The Comment model has a ForeignKey to Restaurant. How can I perform a search in some of the Restaurant fields and in the comment field of the Comment model which returns a list of Restaurant instances?
Thanks
class Restaurant(models.Model):
name = models.CharField(max_length=100)
country=models.ForeignKey(Country)
city=models.ForeignKey(City)
street=models.CharField(max_length=100)
street_number=models.PositiveSmallIntegerField()
postal_code=models.PositiveIntegerField(blank=True, null=True)
slug = models.SlugField(unique=True)
class Comment(models.Model):
user = models.ForeignKey(User)
restaurant = models.ForeignKey(Restaurant)
submit_date = models.DateTimeField(blank = True, null = False)
comment = models.TextField()
I think you should read the manual: http://django-haystack.readthedocs.org/en/latest/tutorial.html
look for multivalue:
class RestaurantIndex(indexes.SearchIndex):
comments = indexes.MultiValueField()
def prepare_comments(self, obj):
return [a for a in obj.comment_set.all()]