I have 2 models called Manufacturer and Car . The Car model has a foreignKey to Manufacturer which mean a many cars can belong to a single Manufacturer.
In the model manfacturer , their is an OneToOneField called showcase which allows a Manufacturer to have a single car to showcase,
How can I show all the Manufacturers which have a car to showcase which mean , show all Manufacturer with a OneToOneField objects.
I tried Manufacturer.objects.filter(showcase=True) but it return an empty dictionary []
class Manufacturer(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=55)
showcase = models.OneToOneField('Car',related_name='Car',blank=True)
class Car(models.Model):
user = models.ForeignKey(User)
Manufacturer = models.ForeignKey(Manufacturer,blank=False,related_name='Manufacturer')
Try Manufacturer.objects.exclude(showcase=None)
also, in your model try to add null=True next to to blank=True in the showcase attribute of the model.
Related
I have a City model which contains names of all cities of my country. Also I have Post model with foreign key set to City model. And I created filter to let user filter Posts by city name:
class PostFilter(django_filters.FilterSet):
class Meta:
model = Post
fields = ['city']
And the problem is that, basically foreign key field contains id of related object and filter will find nothing if user inputs actual city name. So, how do I make it so that when user enters city name, it actually works?
Edit:
My models:
class Cities(models.Model):
name = models.CharField(max_length=63)
class Post(models.Model):
city = models.ForeignKey(Cities, on_delete=models.RESTRICT, null=True, blank=False)
You can filter with:
class PostFilter(django_filters.FilterSet):
city = django_filters.CharFilter(field_name='city__name')
class Meta:
model = Post
fields = []
You can of course add extra fields on which you wish to filter.
I've two models as below.
class Category(models.Model):
title = models.CharField(max_length=55)
class Meta:
verbose_name = 'Food Category'
verbose_name_plural = 'Food Categories'
def __str__(self):
return self.title
class FoodItem(TimeStampWithCreator):
CATEGORY_CHOICES = (
('takeway', 'Takeaway'),
('dine_in', 'Dine In'),
('function', 'Function'),
)
type_menu_select = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='takeway')
category = models.ForeignKey(FoodCategory, on_delete=models.CASCADE)
i want to filter all the categories containing takeaway, I've no idea how to achieve this
You've included category choices in your FoodItem model but the model also has a ForeignKey to a Category model, this isn't needed if the only category objects you have are those three choices (the category field must refer to one of those anyway as it's the ForeignKey). To filter the items by category you would need to use a queryset filter.
https://docs.djangoproject.com/en/3.0/topics/db/queries/#retrieving-specific-objects-with-filters
FoodItem.objects.filter(category=YourCategory)
This is usually the kind of thing I'd like to test in the shell as I don't do it very often. If what you want is actually all Category with a FoodItem that have type_menu_select set to 'takeway' then the following should work (but I haven't tested it):
Category.objects.filter(fooditem__type_menu_select='takeway')
This is using the "reverse" relationship on the ForeignKey and there's more information in the Django docs (search for 'reverse').
Suppose I have the following models:
class Playlist(models.Model):
name = models.TextField()
songs = models.ManyToManyField(Song)
class Song(models.Model):
title = models.TextField()
So a Playlist can have multiple songs and a song can be in multiple playlists.
I want to add an "order" field so that a user can reorder songs in a playlist. I found order_with_respect_to, which appears to be a perfect solution. However, I would need to add that meta option to the Song model, e.g.:
class Song(models.Model):
title = models.TextField()
class Meta:
order_with_respect_to = 'playlists'
Obviously, there is no playlist field specified on Song since I've got the relationship specified in the Playlist model. Is there a way to specify the reverse relationship for order_with_respect_to using related_name? Or could I slap a ForeignKey reference to playlists in the Song model?
order_with_respect_to is (arguably) useful when you have a ForeignKey, but not a ManyToManyField. It works by adding an extra field to the model, but in your case the order varies depending on the Playlist.
The straightforward way to do this in Django is to put the order on an explicitly created through table.
class Playlist(models.Model):
name = models.TextField()
songs = models.ManyToManyField(Song, through='PlaylistSong')
class Song(models.Model):
title = models.TextField()
class PlaylistSong(models.Model):
playlist = models.ForeignKey(Playlist)
song = models.ForeignKey(Song)
order = models.PositiveSmallIntegerField()
So to get the Songs in a Playlist in the right order, you would do something like:
Song.objects.filter(playlistsong__playlist_id=1)
.order_by('playlistsong__order')
Likely this will be a duplicate, but I can't seem to find anything as there's a no useful keywords.
manufacturer is a foreign key in car:
class manufacturer(models.Models):
id = models.AutoField(primary_key=True)
name = models.CharField(unique=True, max_length=64)
class cars(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(unique=True, max_length=64)
manufacturer = models.ForeignKey('Manufacturer')
Right now, I have a car api serialized to all fields it contains (id, name, manufacturer). However, the "manufacturer" field shows the ID of the Manufacturer class.
Question: How do I show the name of the manufacturer in the API for car and not the ID of the manufacturer?
I don't have a lot of experience with django-rest-framework but it looks like you need to create a serializer which will customize the converting of your object to JSON ready to return to the user so that the relationship is taken into account.
Put this in manufacture_app/serializers.py:
from rest_framework import serializers
class CarsSerializer(serializers.ModelSerializer):
manufacturer_name = serializers.RelatedField(source='manufacturer')
class Meta:
model = Cars
fields = ('id', 'name', 'manufacturer_name')
and make sure your __unicode__ function returns the correct name:
class Manufacturer(models.Models):
....
def __unicode__(self):
return self.name
I'm making a cart for a online store. I have a model Product like
#Product
from django.db import models
class Product(models.Model):
title = models.CharField()
attribute = models.ManyToManyField('Attribute')
How can I make attributes models like size, colors with their keys like numbers or choices ('Red', 'Green',...) ?
Have you read up on ManyToManyField?
https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField
You'd need to define an Attribute model class to point to, then add the relationships via the field managers 'add' method.
class Attribute(models.Model):
value = models.CharField(max_length=64)
class Product(models.Model):
title = models.CharField()
attribute = models.ManyToManyField('Attribute')
product = Product.objects.create(title='foobar')
red_attribute = Attribute.objects.create(value='Red')
product.attribute.add(red_attribute)