How to look up a field value using foreignkey in Django - django

I have the following models:
class Camera(models.Model):
url = models.CharField(max_length=300, unique=True)
camera_number = models.IntegerField(null=False, blank=False,
validators=[
MaxValueValidator(1000),
MinValueValidator(1)])
camera_name = models.CharField(max_length=100, null=False, blank=False)
slug = models.SlugField(max_length=100, null=True, blank=False, unique=True)
class BaseImage(models.Model):
url = models.ForeignKey(Camera, on_delete=models.CASCADE)
base_image_filename = "base_images/" + str(Camera.slug) + "/%H"
image = models.ImageField(max_length=300, upload_to=base_image_filename)
What I am trying to do is to create the filename in BaseImage that contains the data in the slug variable of the corresponding Camera record. A camera can have many BaseImages but each BaseImage can only match to one Camera.
What I get in the name is something like "base_images/<django.db.models.query_utils.DeferredAttribute object at 0x7f6006bd9b70>/20/camera_1.jpg".
What do I need to change to get the slug field value as part of the filename ?

You can specify a method and pass a reference to that method:
from django.utils.timezone import now
class BaseImage(models.Model):
def get_image_filename(self, filename):
h = now().strftime('%H')
return f'base_images/{self.url.slug}/{h}/{filename}'
url = models.ForeignKey(Camera, on_delete=models.CASCADE)
image = models.ImageField(max_length=300, upload_to=get_image_filename)

Related

How to save image inside a specific folder(folder name should be id)-DRF

I want to save image inside folder name same as id. Id is a automatic primary key.I tried that when i give post request i got none as a id. how can i achieve this????
models.py
def upload_to(instance, filename):
return 'organization/{instance}/logo/{filename}'.format(filename=filename,
instance=instance.pk)
class Organization(models.Model):
code = models.CharField(max_length=25, null=False, unique=True)
name = models.CharField(max_length=100, null=False)
location = models.ForeignKey(Location, on_delete=models.RESTRICT)
logo_filename = models.ImageField(_("Image"), upload_to=upload_to, null=True)
I know i cant take id before saving into db. there is any possible to do rename when i gave post request?? I got confused over this. Any help appreciable,...
Well I'm not sure of my answer but you can try -
use nested models, if you can -
class Organization(models.Model):
code = models.CharField(max_length=25, null=False, unique=True)
---
---
class OrganizationImage(models.Model):
def upload_to(instance, filename):
return instance.organization
organization= models.OneToOneKey(Organization)
logo_filename = models.FileField(upload_to=upload_to)
And in create method of Organization -
Organization_Image= validated_data.pop(organization_image_data)
organization= Organization.objects.create(validated_data)
O = OrganizationImage.objects.create(organization=organization, **Organization_Image)

Set primary key in Django

The title is not entirely accurate, but I do not know how to explain, so I took a screenshot of where my problem is, and I will try to explain what I am trying to achieve.
I have a vehicle model, and when I create a new vehicle object, the name of vehicles just says Vehicle object (1) How can I change my model, or serializer (or something else) so that will show some unique value of the object.
Here is my model:
class Vehicle(models.Model):
make = models.CharField(max_length=100, blank=True)
model = models.CharField(max_length=300, blank=True)
license_plate = models.CharField(max_length=7, blank=True)
vehicle_type = models.CharField(max_length=20, blank=True)
seats = models.IntegerField(default=4,
validators=[
MaxValueValidator(70),
MinValueValidator(4)],
)
year = models.IntegerField(_('year'), default=datetime.today().year - 10, validators=[
MinValueValidator(1975), max_value_current_year])
inspected = models.BooleanField(default=True)
# fuel_type
# fuel_price
created_at = models.DateTimeField(auto_now_add=True)
You can implement a __str__ method that returns a string, for example:
class Vehicle(models.Model):
# …
def __str__(self):
return f'{self.make} ({self.year})'
You can thus return any string, and that will be presented by default in the Django admin and the drop downs.

save data to another table after creating django

i have two models ImageShoot and Image.
models.py:
class ImageShoot(models.Model):
name = models.CharField(max_length=100)
# image = models.URLField(name=None)
created_at = models.TimeField(auto_now_add=True)
def __str__(self):
return self.name
class Image(models.Model):
license_type = (
('Royalty-Free','Royalty-Free'),
('Rights-Managed','Rights-Managed')
)
image_number = models.CharField(default=random_image_number,max_length=12)
title = models.CharField(max_length = 100)
image = models.ImageField(upload_to = 'home/tboss/Desktop/image' , default = 'home/tboss/Desktop/image/logo.png')
category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE)
shoot = models.ForeignKey(ImageShoot, on_delete=models.CASCADE)
image_keyword = models.TextField(max_length=1000)
credit = models.CharField(max_length=150, null=True)
location = models.CharField(max_length=100, null=True)
license_type = models.CharField(max_length=20,choices=license_type, default='')
uploaded_at = models.TimeField(auto_now_add=True)
def __str__(self):
return self.title
admin.py:
class Imageset(admin.ModelAdmin):
associated_images = ImageShoot.image_set.all()
return associated_images
admin.site.register(Image)
admin.site.register(ImageShoot,Imageset)
what i am trying to achieve that when i create a image it should show on imageshoot also like when i create image in shoot 1. this image should show on shoot 1.
i am not sure which field should i add on imageshoot.
Use Reverse lookup
In Your views you can get all the images associated with the ImageShoot Obj using set.Try this in your shell after briefly going through the docs
associated_images = ImageShoot.image_set.all()
You can also use django orm methods for querysets like filter, count, etc.
Edit:
To display related images you can use this in admin:
#admin.register(ImageShoot)
class Imageset(admin.ModelAdmin):
list_display = ('name', 'created_at', 'associated_images')
def associated_images(self, obj):
return obj.image_set.all() #<----edit
associated_images.admin_order_field = 'imageshoot_image'

Django GET API for image field from different model

I am trying to get the image url from some model. I have made 2 models:
Restaurant model:
class Restaurant(models.Model):
from location.models import Area
from business.models import Business
name = models.CharField(verbose_name=_('Name'), max_length=255, unique=True)
address = models.CharField(verbose_name=_("Address"), max_length=255)
phone = models.CharField(verbose_name=_('Phone Number'), max_length=255)
email = models.EmailField(verbose_name=_('Email'), max_length=255, blank=True, null=True)
website = models.URLField(verbose_name=_('Website / Online Listing Link'), max_length=255, blank=True, null=True)
is_active = models.BooleanField(verbose_name=_("Is Active?"), default=True)
is_veg = models.BooleanField(verbose_name=_('Is Veg?'), default=True)
class Meta:
verbose_name = 'Restaurant'
verbose_name_plural = 'Restaurants'
And Restaurant Image model:
class RestaurantImage(models.Model):
image_type = models.CharField(verbose_name=_('Image Type'), choices=IMAGE_TYPES, max_length=255, default=RESTAURANT)
restaurant = models.ForeignKey(verbose_name=_('Restaurant'), on_delete=models.PROTECT, to=Restaurant)
image = models.ImageField(verbose_name=_('Select Image'), upload_to='media/')
def __str__(self):
return self.restaurant.name + " - " + IMAGE_TYPES_DICT[self.image_type]
class Meta:
verbose_name = 'Restaurant Image'
verbose_name_plural = 'Restaurant Images'
I need to get the image of the restaurant, so I tried to get the image by property method but got UnicodeDecodeError.
#property
def images(self):
images = []
for i in RestaurantImage.objects.filter(restaurant=self.id):
images.append(i.image)
return images
Please help me in getting the image url. Thank you.
So, I found a solution. It works as of now, but still, I would like to explore a better way of fetching an image.
#property
def images(self):
import sys
images = []
for i in RestaurantImage.objects.filter(restaurant=self.id):
file = 'http://' + sys.argv[-1] + '/'
image_path = i.image.file.name
file += image_path[image_path.find('images/'):]
images.append(file)
return images
I basically generated the path of the image.

Django instance - Combine two attribute values in model

Can someone tell me how to combine two or more attribute values of in another field by using instance?
Models.py:
fn_id = models.ForeignKey(FilemNumber, null=True, blank=True)
ln_id = models.ForeignKey(LineNumber, null=True, blank=True)
pn_id = models.ForeignKey(PhotoNumber, null=True, blank=True)
title = models.CharField(max_length=255,blank=True, null=True)
I want to combine fn_id, ln_id and pn_id and save the combination of the three values into field title.
You can do this:
from django import models
class BaseModel(models.Model):
fn_id = models.ForeignKey(FilemNumber, null=True, blank=True)
ln_id = models.ForeignKey(LineNumber, null=True, blank=True)
pn_id = models.ForeignKey(PhotoNumber, null=True, blank=True)
class YourModel(models.Model):
common = models.OneToOneField(BaseModel)
# I suppose that you want to get title, so let define title method
# if obj is an instance of YourModel, you can access title like this:
# obj.title
#property
def title(self):
return '{}{}{}{}'.format(self.id, self.common.fn_id,
self.common.ln_id, self.common.pn_id)
Lets read this article: https://docs.djangoproject.com/en/1.8/ref/models/fields/#onetoonefield