Soft_delete_cascade was applied to the entire model using the django-safedelete library.
However, if you remove the corresponding many to many object as in the code below, it is not deleted from the set of objects.
What should I do?
# models.py
from django.db import models
from safedelete import SOFT_DELETE_CASCADE, HARD_DELETE
from safedelete.models import SafeDeleteModel
class Post(SafeDeleteModel):
_safedelete_policy: int = SOFT_DELETE_CASCADE
category = models.CharField("카테고리", max_length=100, null=True, blank=True)
title = models.CharField("제목", max_length=300, null=True, blank=True)
created_at = models.DateTimeField("생성일시", auto_now_add=True)
updated_at = models.DateTimeField("수정시간", auto_now=True)
tags = models.ManyToManyField("Tag", through="TagPostAssociation", related_name="posts")
def __str__(self):
return f"글(ID:{self.id}/제목:{self.title})"
class Tag(SafeDeleteModel):
_safedelete_policy: int = SOFT_DELETE_CASCADE
value = models.CharField("태그 값", max_length=100)
created_at = models.DateTimeField("생성일시", auto_now_add=True)
updated_at = models.DateTimeField("수정시간", auto_now=True)
class Meta:
verbose_name = verbose_name_plural = "태그"
def __str__(self):
return f"태그(ID:{self.id}/값:{self.value})"
class TagPostAssociation(SafeDeleteModel):
_safedelete_policy: int = HARD_DELETE
tag = models.ForeignKey(to=Tag, verbose_name="태그", on_delete=models.CASCADE)
post = models.ForeignKey(to=Post, verbose_name="글", on_delete=models.CASCADE)
created_at = models.DateTimeField("생성일시", auto_now_add=True)
updated_at = models.DateTimeField("수정시간", auto_now=True)
class Meta:
verbose_name = verbose_name_plural = "글-태그"
def __str__(self):
return f"글{self.post.id})-태그({self.tag.id})"
>>> post = Post.objects.get(id=2)
>>> tag = Tag.objects.get(id=2)
>>> post.tags.all()
<SafeDeleteQueryset [<Tag: 태그(ID:2/값:hair)>, <Tag: 태그(ID:1/값:test)>]>
>>> post.tags.remove(tag)
>>> post.tags.all()
<SafeDeleteQueryset [<Tag: 태그(ID:2/값:hair)>, <Tag: 태그(ID:1/값:test)>]>
I tried to delete the many to many object using the m2m_changed signal, but it didn't work.
Related
There are models, why after python manage.py makemigrations is created only by 1 field in migrations, how to fix it? I tried doing manage.py migrate --fake zero, and doing the migrations again, but nothing.The app is registered in settings.
from django.db import models
from django.urls import reverse
class Category(models.Model):
image = models.ImageField(default='default.png', upload_to='category_image'),
title = models.CharField(max_length=50, db_index = True),
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('category_detail_url', kwargs={'title': self.title})
class Provider(models.Model):
name = models.CharField(max_length=50, db_index = True),
phone_number = models.CharField(max_length=12, db_index = True),
address = models.CharField(max_length=50, db_index = True),
def __str__(self):
return self.name
class Product(models.Model):
title = models.CharField(max_length=50, db_index = True),
receipt_date = models.DateTimeField(auto_now_add=True, blank=True),
quantity_stock = models.IntegerField(),
quantity_store = models.IntegerField(),
purchase_price = models.IntegerField(),
image = models.ImageField(default='default.png', upload_to='product_image'),
provider = models.ForeignKey(Provider, null = True ,related_name='to_provider',on_delete=models.CASCADE),
category = models.ForeignKey(Category, null = True ,related_name='to_category',on_delete=models.CASCADE),
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('product_detail_url', kwargs={'title': self.title})
class Sale(models.Model):
product = models.ForeignKey(Product, related_name='to_product',on_delete=models.CASCADE),
date_of_sale = models.DateTimeField(auto_now_add=True, blank=True),
quantity_goods_sold = models.IntegerField(),
retail_price = models.IntegerField(),
def __str__(self):
return self.id
Your fields should not end with a comma (,). If you add a trailing comma, it will wrap the field in a singleton tuple, and thus Django is then not able to detect the field:
from django.db import models
from django.urls import reverse
class Category(models.Model):
image = models.ImageField(default='default.png', upload_to='category_image')
title = models.CharField(max_length=50, db_index = True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('category_detail_url', kwargs={'title': self.title})
class Provider(models.Model):
name = models.CharField(max_length=50, db_index=True)
phone_number = models.CharField(max_length=12, db_index=True)
address = models.CharField(max_length=50, db_index=True)
def __str__(self):
return self.name
class Product(models.Model):
title = models.CharField(max_length=50, db_index = True)
receipt_date = models.DateTimeField(auto_now_add=True, blank=True)
quantity_stock = models.IntegerField()
quantity_store = models.IntegerField()
purchase_price = models.IntegerField()
image = models.ImageField(default='default.png', upload_to='product_image')
provider = models.ForeignKey(
Provider,
null=True,
related_name='products',
on_delete=models.CASCADE
)
category = models.ForeignKey(
Category,
null=True,
related_name='products',
on_delete=models.CASCADE
)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('product_detail_url', kwargs={'title': self.title})
class Sale(models.Model):
product = models.ForeignKey(
Product,
related_name='sales',
on_delete=models.CASCADE
)
date_of_sale = models.DateTimeField(auto_now_add=True, blank=True)
quantity_goods_sold = models.IntegerField()
retail_price = models.IntegerField()
def __str__(self):
return self.id
If this question is stupid I'm sorry, but I couldn't really find anything useful on Google.
So I have a model made up of two fields.
I want to create a model with some other fields, but two of them should be the ones from the previous one. Is there any way to obtain this?
Code:
from django.db import models
from django.contrib.auth.models import User
from datetime import date
# Create your models here.
class CORMeserii(models.Model):
CodCOR = models.CharField(max_length=25, primary_key=True, unique=True)
MeserieCor = models.CharField(max_length=50, unique=True)
class Oferta(models.Model):
solicitant = models.ForeignKey(User, on_delete=models.CASCADE)
cor = models.ForeignKey(CORMeserii, max_length=25, on_delete=models.CASCADE)
meserie = models.ForeignKey(CORMeserii, max_length=50, to_field='MeserieCor', on_delete=models.CASCADE)
dataSolicitare = models.DateField(default=date.today)
denumireMeserie = models.CharField(max_length=50)
locuri = models.IntegerField()
agentEconomic = models.CharField(max_length=50)
adresa = models.CharField(max_length=150)
dataExpirare = models.DateField()
experientaSolicitata = models.CharField(max_length=200)
studiiSolicitate = models.CharField(max_length=200)
judet = models.CharField(max_length=20)
localitate = models.CharField(max_length=25)
telefon = models.CharField(max_length=12)
emailContact = models.EmailField(max_length=40)
rezolvata = models.BooleanField(default=False)
def __str__(self):
return self.cor
I thought this might work, but I get these errors:
from django.db import models
from django.contrib.auth.models import User
from datetime import date
from .validators import validate_file_size
# Create your models here.
class CORMeserii(models.Model):
CodCOR = models.CharField(max_length=25, primary_key=True, unique=True)
MeserieCor = models.CharField(max_length=50, unique=True)
class Oferta(models.Model):
solicitant = models.ForeignKey(User, on_delete=models.CASCADE)
cor = models.ForeignKey(CORMeserii, max_length=25, on_delete=models.CASCADE)
meserie = models.ForeignKey(CORMeserii, max_length=50, to_field='MeserieCor', on_delete=models.CASCADE)
dataSolicitare = models.DateField(default=date.today)
denumireMeserie = models.CharField(max_length=50)
locuri = models.IntegerField()
agentEconomic = models.CharField(max_length=50)
adresa = models.CharField(max_length=150)
dataExpirare = models.DateField()
experientaSolicitata = models.CharField(max_length=200)
studiiSolicitate = models.CharField(max_length=200)
judet = models.CharField(max_length=20)
localitate = models.CharField(max_length=25)
telefon = models.CharField(max_length=12)
emailContact = models.EmailField(max_length=40)
rezolvata = models.BooleanField(default=False)
def __str__(self):
return self.cor
I have few classes:
class Correspondent(models.Model):
title = models.CharField(max_length=60)
class Subject(models.Model):
title = models.CharField(max_length=60)
class Letter(models.Model):
correspondent = models.ForeignKey(Correspondent,
on_delete=models.SET_NULL, null=True)
subject = models.ForeignKey(Subject, on_delete=models.SET_NULL, null=True)
description = models.TextField(max_length=600, blank=True)
case_number = models.CharField(max_length=100, blank=True)
inventory_number = models.CharField(max_length=100, blank=True)
note = models.TextField(max_length=300, blank=True)
user = models.ForeignKey(User, editable=False, on_delete=models.SET_NULL, null=True)
date = models.DateField(default=datetime.date.today)
date_creation = models.DateTimeField(auto_now_add=True)
class IncomingLetter(Letter):
response_to = models.ForeignKey('OutgoingLetter', on_delete=models.SET_NULL, null=True, blank=True)
outgoing_number = models.CharField(max_length=120, blank=True)
incoming_number = models.CharField(max_length=120, blank=True)
class OutgoingLetter(Letter):
response_to = models.ForeignKey(IncomingLetter, on_delete=models.SET_NULL, null=True, blank=True)
outgoing_number = models.CharField(max_length=120, blank=True)
and in a view i trying to send json with serialized class B instances:
from django.http import JsonResponse
from django.core import serializers
from .models import IncomingLetter
def index(request):
....
some_data = IncomingLetter.objects.all()
serialized_data = serializers.serialize('json', some_data)
return JsonResponse(json.dumps(serialized_data), safe=False)
and response missed all Letter fields in json. Is there a way to not serialize it manually?
serialized_data == {"model": "letters.incomingletter", "pk": 4, "fields": {"response_to": 3, "outgoing_number": "12312321", "incoming_number": "123123"}}
SOLVED # (not sure)
I wrote simple serializer, but not sure is this cleanest way(many unnecessary fields, but it easy to clean):
class LetterSerializer:
def __init__(self):
self.serialized_data = {}
def serialize(self, data):
for idx, instance in enumerate(data):
serialized_instance_data = {}
for key, value in instance.__dict__.items():
serialized_instance_data[key] = str(value)
self.serialized_data[idx] = serialized_instance_data
return self.serialized_data
I have serializer in Django rest framework as follows:
class StateSerializer(serializers.ModelSerializer):
kilometers = Field(source='mileage')
pictures = StatePictureSerializer(many=True, read_only=True)
class Meta:
model = Inspection # Options
fields = ('kilometers', 'inspection_date', 'pictures')
And StatePictureSerializer is as follows:
class StatePictureSerializer(serializers.ModelSerializer):
blob_url = Field(source='public_url')
class Meta:
model = Inspection_Picture
fields = ('blob_url', )
As result I get something as follows:
{
"kilometers": 64431,
"inspection_date": null,
"pictures": [
{"blob_url": "path/to/photo"},
{"blob_url": "path/to/photo"},
{"blob_url": "path/to/photo"},
{"blob_url": "path/to/photo"},
{"blob_url": "path/to/photo"}
]
}
Thus, pictures is an array of objects.
What I want is an array of strings, for example:
"pictures": ["path/to/photo", "path/to/photo", "path/to/photo", "path/to/photo", "path/to/photo"]
Any idea how to do that?
EDIT
Inspection model is as follows:
class Inspection(models.Model):
customerReference = models.CharField(max_length=50, blank=True, null=True)
extraReference = models.CharField(max_length=50, blank=True, null=True)
itemReference = models.IntegerField(blank=True, null=True)
vehicle = models.ForeignKey(to=Vehicle)
mileage = models.IntegerField()
timeStamp = models.DateTimeField(auto_now_add=True)
inspection_date = models.DateTimeField(null=True)
features = models.ManyToManyField(to=Feature)
pictures = models.ManyToManyField(to=Images, through="Inspection_Picture")
damages = models.ManyToManyField(to=Damage)
parts = models.ManyToManyField(to=Part)
checks = models.ManyToManyField(to=CheckType, through=Inspection_Check)
featuresFlat = models.ManyToManyField(to=FeatureFlat, through=Inspection_FeatureFlat)
And Images model is as follows:
class Images(models.Model):
"""Model for storing uploaded photos"""
filename = models.CharField(max_length=255)
extension = models.CharField(max_length=40)
key_data = models.CharField(max_length=90, unique=True, blank=True, null=True)
upload_date = models.DateTimeField(auto_now_add=True)
upload_identification = models.CharField(max_length=50, blank=True, null=True)
url = models.CharField(max_length=1024, blank=True, null=True)
stored = models.BooleanField(default=False)
thumbnailed = models.BooleanField(default=False)
thumbnailed_treated = models.BooleanField(default=False)
protected = models.BooleanField(default=False)
source = models.CharField(max_length=50, blank=True, null=True)
#property
def key_generate(self):
"""returns a string based unique key with length 80 chars"""
while 1:
key = str(random.getrandbits(256))
try:
Images.objects.get(key=key)
except:
return key
def __unicode__(self):
return self.upload_identification
def public_url(self):
return settings.AZURE_URL_FULL + self.url
I think in your case SerializerMethodField would be a right choice as follows. There may be <field_name> mismatch in the code below. Please make it working according your model. I assume the field names based on your serializer above.
class StateSerializer(serializers.ModelSerializer):
kilometers = Field(source='mileage')
pictures = serializers.SerializerMethodField('get_pictures')
class Meta:
model = Inspection # Options
fields = ('kilometers', 'inspection_date', 'pictures')
def get_pictures(self, obj):
return [each.public_url() for each in obj.pictures.all() ]
How To assign bed to Patient Django?
when I try to assign bed to Patient at that time in bedconfig automatically select Patient Name
then wardconfig file open but Patient name is blant, it must be autoselected Patient name
view this image When click on assign bed
but Patient name is blant, it must be autoselected Patient name
models.py Patient model
class Patient(Auditable):
aadhar_no = models.CharField(max_length=12, blank=True,unique=True)
fullname = models.CharField(max_length=50)
firstname = models.CharField(max_length=30)
middlename = models.CharField(max_length=30)
lastname = models.CharField(max_length=30)
CATEGORY_GENDER= (('Male', 'Male'), ('Female', 'Female'))
gender = models.CharField(max_length=6, choices=CATEGORY_GENDER)
CATEGORY_BG= (('Not known','Not known'),('A+', 'A+'), ('A-', 'A-'),('B+', 'B+'),('B-', 'B-'),('AB+', 'AB+'),('AB-','AB-'),('O+','O+'), ('O-','O-'))
blood_group = models.CharField(max_length=10, choices=CATEGORY_BG)
dob = models.DateField() #Date of birth
photo = models.ImageField(upload_to="Patient/", null=True, blank=True)
education = models.CharField(max_length=15, null=True, blank=True)
CATEGORY_OCC= (('Service', 'Service'), ('Retired', 'Retired'),('Housewife', 'Housewife'), ('Business','Business'),('other','other'))
occupation = models.CharField(max_length=15, choices=CATEGORY_OCC,null=True, blank=True) #service, retired, Housewife, Business, others
current_address = models.TextField()
mobile_number = models.CharField(max_length=12)
mobile_number2 = models.CharField(max_length=12, null=True, blank=True)
phone_number = models.CharField(max_length=12, null=True, blank=True)
email = models.CharField(max_length=30, null=True, blank=True)
country = models.ForeignKey(Country , null=True, blank=True, )
state = models.ForeignKey(State , null=True, blank=True)
district = models.ForeignKey(District , null=True, blank=True)
city = models.ForeignKey(City ,null=True, blank=True)
recreational_drugs= models.BooleanField(default=False) #alocohol, smoking,coffine etc.
current_insurance = models.BooleanField(default=False)
#family = models.ForeignKey(Family) # Family
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self): # __unicode__ on Python 2
# return self.fullname
return str(self.fullname)
class Meta:
verbose_name_plural = "Patient"
models.py WardConfog
class WardConfig(Auditable):
bed = models.ForeignKey(Bed)
ward = models.ForeignKey(Ward)
patient=models.ForeignKey(Patient)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
#def __str__(self): # __unicode__ on Python 2
#return self.name
class Meta:
verbose_name_plural = "Wardconfig"
Views.py PatientCreate(CreateView)
class PatientCreate(CreateView):
model = Patient
form_class = PatientForm
def get_success_url(self):
return reverse_lazy( 'patient')
def form_valid(self,PatientForm):
PatientForm.save()
return HttpResponseRedirect(self.get_success_url())
def form_invalid(self, PatientForm):
return self.render_to_response(self.get_context_data(form=PatientForm))
Views.py
class WardConfig(Auditable):
bed = models.ForeignKey(Bed)
ward = models.ForeignKey(Ward)
patient=models.ForeignKey(Patient)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
#def __str__(self): # __unicode__ on Python 2
#return self.name
class Meta:
verbose_name_plural = "Wardconfig"
please Guys Help me how auto select Patient Name IN Wardconfig when assign bed
Sorry for English
You can give the view you are using to add a WardConfig record a get_initial method. This assumes you are passing a patient_id kwarg in the URL:
def get_initial(self):
patient = get_object_or_404(Patient, pk=self.kwargs.get('patient_id'))
return {
'patient': patient,
}