I am new to Python and Django.
I am trying to build myself very simple blog application.
So I have this 2 models :
class Tag(models.Model):
name = models.CharField(max_length=250)
slug = models.SlugField(unique=True)
def __unicode__(self):
return self.name
class Blogpost(models.Model):
title = models.CharField(max_length=300)
content = tinymce_models.HTMLField()
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField(Tag)
def __unicode__(self):
return self.title
As you can see Blogpost can contain many Tags,
my question is how can I query Blogpost.objects.all() to get Blogposts list by specific Tag?
Thank you.
I think related manager is your answer
t = Tag.objects.get(name="Some tag")
t.blogpost_set.all()
Related
I'm making a searchbar for a site I'm working on and I'm having trouble when I want to filter different fields from different models (related between them) Here are my models:
class Project(models.Model):
name = models.CharField(max_length=250)
objective = models.CharField(max_length=250)
description = models.TextField()
launching = models.CharField(max_length=100, null=True, blank=True)
image = models.ImageField(
upload_to='imgs/', null=True, blank=True)
image_thumbnail = models.ImageField(
upload_to='thumbnails/', null=True, blank=True)
slug = models.CharField(max_length=250)
class Meta:
db_table = 'project'
def __str__(self):
return self.name
class Institution(models.Model):
name = models.CharField(max_length=250)
project = models.ManyToManyField(Proyecto)
class Meta:
db_table = 'institution'
def __str__(self):
return self.name
And I want to be able to search by the name of the project or the institution, but my code only takes the institution's name.
def searchbar(request):
if request.method == 'GET':
search = request.GET.get('search')
post = Project.objects.all().filter(name__icontains=search, institution__name__icontains=search)
return render(request, 'searchbar.html', {'post': post, 'search': search})
How can I search for all the projects that match by its name OR the institution's name?
BTW, I'm using SQL, not sure if it's relevant, but I thought I should add that info.
You can .filter(…) [Django-doc] with Q objects [Django-doc]:
from django.db.models import Q
Project.objects.filter(Q(name__icontains=search) | Q(institution__name__icontains=search))
or you can work with the _connector parameter:
from django.db.models import Q
Project.objects.filter(
name__icontains=search,
institution__name__icontains=search,
_connector=Q.OR
)
I'm new to django (and python) and I have a question.
I have this model:
class Material(models.Model):
name = models.CharField(max_length=256, blank=True)
description = models.TextField(null=True, blank=True)
def __str__(self):
return self.name
class Meta:
abstract = True
and
class Experiments(models.Model):
title = models.CharField(max_length=200)
experiment = models.TextField(null=True, blank=True)
def __str__(self):
return self.title
I want to query it so I have only have the Materials used in the Experiments model. I was reading about Q objects but I'm not sure how to use it. I appreciate any help!
I would like to return in str method of the Chapter, title of the Chapter and title of the Book (from book model). I need it for better display at the admin pages. How to do that?
Should I create some new method in Book or use Model instance reference https://docs.djangoproject.com/en/1.11/ref/models/instances/#model-instance-methods ?
Or maybe I should use Retrieving specific objects with filters?
https://docs.djangoproject.com/en/1.11/topics/db/queries/#retrieving-objects
I am new to the django, thank you in advance for the solutions.
class Book(models.Model):
author = models.CharField(max_length=200)
title = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
def __str__(self):
return self.title+" ("+self.author+")"
def book_author(self):
return self.author
class Chapter(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE)
title = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
body = models.TextField()
hierarchy = models.IntegerField()
sort = models.IntegerField(unique=True)
def __str__(self):
print(repr(Book))
print(repr(Book.author))
# print(repr(Book.objects.all().filter(id==1)))
# print(repr(Book.objects.get(id=1)))
print(repr(Book.book_author(self)))
return self.title+"(book: "+")"
def __str__(self):
return '%s (%s)' % (self.title, self.book.title,)
To print your object data in admin panel more nicely you should overide __str__ method for your models.
For example your code should look like:
class Book(models.Model):
author = models.CharField(max_length=200)
title = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
def __str__(self):
return 'Book with title: {} writen by {}'.format(self.title, self.author)
`
What I want to do is simply match the images to the department model through tags. How do I write a view for my department page to do this? I have looked everywhere but can't find the answer. Please help!
Models:
class Tag(models.Model):
tag_title = models.CharField(max_length=200)
slug = models.CharField(max_length=200)
def __str__(self):
return self.tag_title
class Image(models.Model):
image_url = models.CharField(max_length=200)
title = models.CharField(max_length=200)
tags = models.ManyToManyField(Tag, blank=True)
def __str__(self):
return self.title
class Department(models.Model):
page_title = models.CharField(max_length=200)
slug = models.CharField(max_length=200)
content = models.TextField()
tags = models.ManyToManyField(Tag, blank=True)
def __str__(self):
return self.page_title
Try this:
Image.objects.filter(tags__department=d) #where d is your deparment.
Something like this should work:
Given a Department object department_obj:
images = Image.objects.filter(tags__in=department_obj.tags.all())
Hi I'm a Django newbie writing my first application. I have a basic model:
from django.db import models
from django_extensions.db.fields import AutoSlugField
class Tag(models.Model):
name = models.CharField(max_length=100)
slug = AutoSlugField(populate_from='name', unique=True)
class Listings(models.Model):
listing = models.CharField(max_length=50)
description = models.CharField(max_length=500)
email = models.EmailField(max_length=75)
tag = models.ManyToManyField(Tag)
pub_date = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.listing
I've added a few tags from terminal but all are surfacing as Tag Object. How do I get the name of the tag to show?
Also, how would I enable the admin to add tags, instead of adding via terminal each time?
Thanks very much!
You were missing a unicode attribute in the Tag model
class Tag(models.Model):
name = models.CharField(max_length=100)
slug = AutoSlugField(populate_from='name', unique=True)
def __unicode__(self):
return "%s"% self.name
Also, Fix the indentation of your unicode block for Listings model
class Listings(models.Model):
listing = models.CharField(max_length=50)
description = models.CharField(max_length=500)
email = models.EmailField(max_length=75)
tag = models.ManyToManyField(Tag)
pub_date = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.listing