Django Get object if it has foreignkey - python

I'm creating an article app (in django) where articles can have images. I want to get articles only when they have at least one image. I already tried:
Article.objects.all().annotate(num_extra=Count("Image")).order_by("-num_extra")
But that only returned a sorted queryset starting with the most images and thats not wat I want.
Is there a way to do that?
My models.py
class Article(models.Model):
id = models.CharField(max_length=8, default=None, primary_key=True, blank=True, verbose_name="ID", unique=True, editable=False)
Category = models.ForeignKey(Category, default=None, on_delete=models.CASCADE, verbose_name="Kategorie")
text = models.CharField(max_length=678543)
#And some other fields
class Image(models.Model):
Article = models.ForeignKey(Article, on_delete=models.CASCADE, default=None, verbose_name="Artikel")
authors = models.ManyToManyField(User, verbose_name="Autor", default=None, blank=True)
#And some other fields

You can filter article by which image is not present at Image
Try this:
Article.objects.filter(image__isnull=False)

Related

Django model how to do many to one mapping?

I am trying to map multiple field to same field in vendor and menu class. If I map using foreign key like below it works. But this is not what I want.
class OrderItem_Mon(models.Model):
vendor_name = models.ForeignKey(Vendor, on_delete=models.SET_NULL, null=True)
menu_name = models.ForeignKey(Menu, on_delete=models.SET_NULL, null=True)
date_created = models.DateTimeField('date created', auto_now_add=True)
note = models.CharField('note', max_length=255, null=True, blank=True)
I need to map multiple field to same field of specific table like this.
class OrderItem_Mon(models.Model):
vendor_name_1 = models.ForeignKey(Vendor, db_column='vendor_name', on_delete=models.SET_NULL, null=True)
menu_name_1 = models.ForeignKey(Menu, db_column='menu_name',on_delete=models.SET_NULL, null=True)
vendor_name_2 = models.ForeignKey(Vendor, db_column='vendor_name',on_delete=models.SET_NULL, null=True)
menu_name_2 = models.ForeignKey(Menu, db_column='menu_name', on_delete=models.SET_NULL, null=True)
date_created = models.DateTimeField('date created', auto_now_add=True)
note = models.CharField('note', max_length=255, null=True, blank=True)
However, it does not work. How do I make this work? Basically, I need to make new form that have dropbox that gets value from vendor and menu model to each field. Help
You need to add related_name attribute for foreign key model fields and give different names.
The error is due to the same model used as a Foreign key for multiple fields. So.it makes an issue during migration. Just setting the different .related_name wont make any issue.

How do I model a many to many relationship in Django Rest Framework?

I need to model a many to many relationship.
I've read some documentation, but I don't know how to model.
I'll give you an example of what I want to do.
I have two entities, Album and song.
They have a many to many relationship.
class Song(models.Model):
name = models.CharField(unique=True, max_length=255)
class Album(models.Model):
nombre = models.CharField(unique=True, max_length=255)
songs = models.ManyToManyField(Song, blank=True)
The user in the frontend, provides me the data of an album that I must save.
It provides me the name of the album and the name of the songs.
How could I model it on the serializers?
Nothing runs.
I think you can delete that blank=True i think it automatically can be blank.
class Song(models.Model):
name = models.CharField(unique=True, max_length=255)
class Album(models.Model):
nombre = models.CharField(unique=True, max_length=255)
songs = models.ManyToManyField(Song, related_name='songs', blank=True)
and you can make the serializer.
Django will create a table for many to many relationships. You can do this by yourself as well with customized fields. For example, you may like to save the order for songs in an album:
class Song(models.Model):
name = models.CharField(unique=True, max_length=255)
class Album(models.Model):
name = models.CharField(unique=True, max_length=255)
class AlbumSong(models.Model):
album = models.ForeignKey('Album', null=False, on_delete=models.PROTECT)
song = models.ForeignKey('Song', null=False, on_delete=models.PROTECT)
order = models.PositiveIntegerField(null=False)
removed = Bit1BooleanField(null=False, default=False)

Want to achieve searching function in django admin page for multiple tables

I am currently working on django 2.0.2 admin page. I have three tables, which are 'metabolites', 'gene' and 'reactions.' The structure of each class is defined as below:
class Genes(models.Model):
id = models.CharField(primary_key=True, max_length=255)
name = models.CharField(max_length=255, blank=True, null=True)
notes = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'Genes'
class Metabolites(models.Model):
id = models.CharField(primary_key=True, max_length=255)
name = models.CharField(max_length=255, blank=True, null=True)
compartment = models.CharField(max_length=255, blank=True, null=True)
charge = models.CharField(max_length=255, blank=True, null=True)
formula = models.CharField(max_length=255, blank=True, null=True)
notes = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'Metabolites'
class Reactions(models.Model):
id = models.CharField(max_length=255, primary_key=True)
name = models.CharField(max_length=255, blank=True, null=True)
metabolites = models.TextField(blank=True, null=True)
lower_bound = models.CharField(max_length=255, blank=True, null=True)
upper_bound = models.CharField(max_length=255, blank=True, null=True)
gene_reaction_rule = models.TextField(blank=True, null=True)
subsystem = models.CharField(max_length=255, blank=True, null=True)
notes = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'Reactions'
As you can see, the 'reaction' class also included 'metabolites' component. A typically reaction actually involved more than two metabolites. What I want to do is, create a search field on the admin page(not the page of each class), and when I type in the reaction id, the searching result can display the reaction and all the involved metabolites, and when I type in a metabolites, the searching result can display this metabolite's information and all reactions this metabolites involved.
Is that possible? Can somebody tell me how to do this?
Thank you for helping me!
EDIT:
This describes the "old school" way of accomplishing this. This appears to be a use case for django's many to many fields. I have not run into this need in my project; so, I have not, yet, studied up the many to many capabilities in django. I recommend reading the django docs for how to use many to many fields.
The way described here will accomplish the desired connections in the data. However, I suspect that the django admin will be easier and more straightforward to set up using a many to many field.
end edit
You want to make another model for metabolites_in_reaction that only contains its own primary key, a foreign key to the reaction and foreign key to metabolites.
class ReactionMetabolites(models.Model):
reaction = models.ForeignKey(Reactions, on_delete=models.CASCADE)
metabolite = models.ForeignKey(Metabolites, on_delete=models.CASCADE)
A many to many field may also be appropriate here; I have not really figured out the many to many fields yet.
Edit 2:
After making these changes in your models, you will need to make and apply migrations to apply the changes to your database.
python manage.py makemigrations
python manage.py migrate

Add blog posts without category in django 1.11

I want to be able to add some blog posts with categories and some without categories in django. with this models django admin won't let me add blog posts without a category. Thanks.
from django.db import models
from django.db.models import permalink
class Blog(models.Model):
title = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
body = models.TextField()
pub_date = models.DateField(db_index=True, auto_now_add=True)
# Many-to-one relationship.
category = models.ForeignKey('blog.Category')
class Category(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
Update your model like this:
category = models.ForeignKey('blog.Category', blank=True, null=True)
blank=True allow forms to have a blank value.
null=True allows a null value in the database.
Edit: here is the documentation

What the right way to make this kind of complicated request over ORM?

Lets say we have follow models:
class Bundle(models.Model):
# ...
class Order(models.Model):
# ...
bundle = models.ForeignKey(
Bundle, on_delete=models.CASCADE,
verbose_name=_('бандл'),
related_name='orders')
class CommentThread(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL, verbose_name=_('user'),
blank=True, null=True, related_name="%(class)s_comments",
on_delete=models.SET_NULL)
content_type = models.ForeignKey(
ContentType,
verbose_name=_('content type'),
related_name="content_type_set_for_%(class)s",
on_delete=models.CASCADE)
object_pk = models.TextField(_('object ID'))
content_object = GenericForeignKey(ct_field="content_type", fk_field="object_pk")
datetime = models.DateTimeField(verbose_name=_('last time thread was read'), default=None,
null=True, blank=True)
class Comments(models.Model):
content_type = models.ForeignKey(
ContentType,
verbose_name=_('content type'),
related_name="content_type_set_for_%(class)s",
on_delete=models.CASCADE)
user = models.ForeignKey(
settings.AUTH_USER_MODEL, verbose_name=_('user'),
blank=True, null=True, related_name="%(class)s_comments",
on_delete=models.SET_NULL)
content_object = GenericForeignKey(ct_field="content_type", fk_field="object_pk")
object_pk = models.TextField(_('object ID'))
text = models.TextField(max_length=COMMENT_MAX_LENGTH)
submit_date = models.DateTimeField(_('date/time submitted'), default=None, db_index=True)
By design, we may attach comments to everyone models, but in this case, we attach comments to Bundle over content type \ object id generics. To implement "read \ unread comments for each user in the thread" we use CommentThread model with the same content type object generic (I know, this is terrible idea, but this is kind of legacy code).
If Bundle instance have attached comments with comment.submit_date > comment_thread.objects.filter(user=user, content_object=bundle).datetimethis mean comment is new for current user.
So, I need to get list of Orders with new comments for user, ordered by time of submitting last comment, attached to Order.bundle with count of this comments for each Order
Question is: what the right way make this request by ORM? Is it possible?

Categories