matching manytomany fields in django - django

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())

Related

Django Model, Multi value / Admin Area

I have start fresh with Django.
I am creating a blog and I need a hint now.
I want to add tags to my posts.
So I created a model for my tags:
class Tag(models.Model):
name = models.CharField(max_length=200, unique=True)
def __str__(self):
return self.name
This is my Post Model
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
What is the best way, that the user can select in the admin area tags for the post and more than one or create a new tag?
In the Post class, add a field ManyToMany
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
tag = models.ManyToManyField(Tag)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
You are looking for InlineModelAdmin particulary section regarding
Working with many-to-many models
something as following:
class TagInline(admin.TabularInline):
model = Post.tags.through
class PostAdmin(admin.ModelAdmin):
inlines = [
TagInline,
]
Also you are missing relationship on your model which should be ManyToMany
class Post(models.Model):
...
tags = models.ManyToManyField(Tag)

How to query a django model using another model?

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!

Reference to another field in model.py // Django

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)
`

Learning ManytoMany Field in Django

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

Django query based on ManyToManyField

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()