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
Related
I need to perform FTS across multiple different models. I want to get any model type in search result.
I would like to sort results by rank, to get most relevant result. I can run search one by one, but not sure how can I combine results, especially preserving rank relevancy.
Here are models, its an example from Making queries manual page.
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
class Author(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField()
class Entry(models.Model):
blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateField()
mod_date = models.DateField()
authors = models.ManyToManyField(Author)
number_of_comments = models.IntegerField()
number_of_pingbacks = models.IntegerField()
rating = models.IntegerField()
You can combine your multiple querysets into one with something like this.
from itertools import chain
blogs = Blog.objects.filter(...)
authors = Author.objects.filter(...)
entries = Entry.objects.search(...)
chain = chain(blog_results, lesson_results, profile_results)
qs = sorted(chain, key=lambda instance: instance.pk, reverse=True)
I know how I can count things with annotate (in my view) but I would like to do the same in model (so it would be more reusable).
For example (lets take an example from django documentation) I have this model:
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
class Publisher(models.Model):
name = models.CharField(max_length=300)
class Book(models.Model):
name = models.CharField(max_length=300)
pages = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
rating = models.FloatField()
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
pubdate = models.DateField()
class Store(models.Model):
name = models.CharField(max_length=300)
books = models.ManyToManyField(Book)
and I can use in view this:
from django.db.models import Count
pubs = Publisher.objects.annotate(num_books=Count('book'))
But how I do that in model?
I know this question is pretty basic (probably) but I'm pretty much beginner in django.
Thanks for answers!
You can use custom managers:
Django docs: Managers
class BookManager(models.Manager):
def get_queryset(self):
return super().get_queryset().annotate(num_books=Count('book'))
class Publisher(models.Model):
name = models.CharField(max_length=300)
books = BookManager()
Now you can call it like this:
pubs = Publisher.books.all()
And you will have num_books with your objects.
You can use classmethod for this.
class Publisher(models.Model):
...
#classmethod
def get_book_count(cls):
return cls.objects.annotate(num_books=Count('book'))
You can call this method as
pubs = Publisher.get_book_count()
Edit - Also check out the answer by #Navid2zp which might be a better solution for you.
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()
models.py:
class Post(models.Model):
author = models.ForeignKey('User')
text = models.TextField(max_length=320)
created_date = models.DateTimeField(default=timezone.now)
class Likes(models.Model):
post = models.ForeignKey('Post')
liker = models.ForeignKey('User')
created_date = models.DateTimeField(default=timezone.now)
class Meta:
unique_together = ('post', 'liker')
I want to Get newest posts which their likes are more than 70. how can I write that query set with django orm ?
You need to annotate a count of the number of likes then filter on that
Post.objects.annotate(num_likes=Count('likes')).filter(num_likes__gt=70).order_by('-created_date')
You can do QV like this example.
qv = Likes.objects.filter(liker__gt = 70).all()
out = Post.objects.filter(id__in=qv).order_by('-created_at')
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()]