Many to Many relation with custom table in Django - django

I have two models with many to many relationships with custom table such as Clinic and Doctor and custom table DoctorClinic.
how could I get the list of Doctors based on Clinics?
this is my views.py
class ClinicDetailView(generic.DetailView):
model = Clinic
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['doctor_list'] = self.doctor_set.annotate(
shift=F('doctor_list__shift'),
timming=F('doctor_list__timming')
return context
I got the error object has no attribute doctor_set
here is my models.py
class Clinic(models.Model):
name = models.CharField(max_length = 256)
area = models.ForeignKey(Area, on_delete=models.CASCADE,default=None,null=True)
city = models.ForeignKey(City, on_delete=models.CASCADE,default=None,null=True)
address = models.TextField()
contact = models.CharField(max_length = 18)
category = models.CharField(max_length=30,choices = CHTYPE)
lat = models.FloatField()
lon = models.FloatField()
class Doctor(models.Model):
name = models.CharField(max_length = 256)
speciality = models.CharField(max_length = 256)
contact = models.CharField(max_length = 12)
speciality = models.ForeignKey(Speciality, on_delete=models.CASCADE)
clinic_hospital = models.ManyToManyField(Clinic, through='DoctorHospital')
class DoctorHospital(models.Model):
clinic = models.ForeignKey(ClinicHospital, on_delete=models.CASCADE)
doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE)
shift = models.CharField(max_length=10)
# time_from = models.DateTimeField(auto_now_add=False,blank=True)
# time_to = models.DateTimeField( auto_now_add=False,blank=True)
timing = models.CharField(max_length=20,blank=True)
and here is my urls.py
path('clinichospital/<int:pk>/',views.ClinicHospitalDetailView.as_view(),name = 'clinichospital_detail')
please help me how can doctor list I show.

Try this out:
class ClinicDetailView(generic.DetailView):
model = Clinic
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
client_id = self.kwargs['pk'] # Pull id out of url
client = Client.objects.get(id=client_id)
context['doctor_list'] = client.doctor_set.annotate(
shift=F('doctor_list__shift'),
timming=F('doctor_list__timming')
) # Missing bracket
return context

Related

how to add new foreign key in my old django models?

I have a model name Employee now i want to add a new fields in this model which will be a foreign key of Department model.I try to solve it the following way but i get error like
django.db.utils.IntegrityError: The row in table 'employee_verification_employee' with primary key 'UP-0319001' has an invalid foreign key: employee_verification_employee.department_id contains a value '03' that does not have a corresponding value in employee_verification_department.id.
class Department(models.Model):
name = models.CharField(max_length=100)
id = models.CharField(primary_key=True,max_length=10)
class Employee(models.Model):
name = models.CharField(max_length=100)
department = models.CharField(max_length=100,choices = Departments)
date_of_joining = models.DateField()
employeed = models.BooleanField(default = True)
email = models.EmailField(max_length = 254)
blood_group = models.CharField(max_length=50)
designation = models.CharField(max_length=100)
image = models.ImageField(upload_to='employee_images',default = "")
number = PhoneField(blank=True, help_text='Enter Contact Number')
emergency_number = PhoneField(blank=True, help_text='Enter Contact Number')
id = models.CharField(primary_key=True, max_length=200)
department_new = models.ForeignKey(Department,on_delete=models.CASCADE,blank=True)
def save(self, *args, **kwargs):
if not self.id:
nth_member = Employee.objects.filter(department = self.department).count()+1
self.id = "UP-" + self.department + self.date_of_joining.strftime("%y")+"{:03d}".format(nth_member)
print(self.id)
super(Employee, self).save(*args, **kwargs)
def __str__(self):
return self.name + "--"+ self.designation``
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/xdRMd.png
As #trigo said, all you need is:
class Department(models.Model):
name = models.CharField(max_length=100)
class Employee(models.Model):
name = models.CharField(max_length=100)
department = models.CharField(max_length=100,choices = Departments)
date_of_joining = models.DateField()
employeed = models.BooleanField(default = True)
email = models.EmailField(max_length = 254)
blood_group = models.CharField(max_length=50)
designation = models.CharField(max_length=100)
image = models.ImageField(upload_to='employee_images',default = "")
number = PhoneField(blank=True, help_text='Enter Contact Number')
emergency_number = PhoneField(blank=True, help_text='Enter Contact Number')
department_new = models.ForeignKey(Department,on_delete=models.CASCADE,blank=True)
And Django will take care of the rest (ids).

Cannot assign "'user_name'": "Class.user" must be a "Account_class" instance

enter image descripI am getting this error when I try to make a post requesttion here
How to can I solve this problem?
Here is my model:
class Coffee(models.Model):
name = models.CharField(max_length=60)
ratings = models.CharField(max_length=5)
taste = models.TextField()
coffeeType = models.CharField(max_length=60)
price = models.CharField(max_length=60)
img = models.CharField(max_length=200)
updated_at = models.DateTimeField(auto_now_add=True)
shopName = models.CharField(max_length=60)
coffeeShopID = models.CharField(max_length=200)
location = models.CharField(max_length=200)
user = models.ForeignKey(Account, on_delete=models.CASCADE, null=False, blank=False, related_name='user')
def __str__(self):
return self.name[0:50]
class Meta:
ordering = ['-updated_at']
Here is the serializer of that model:
class CoffeeSerializers(serializers.ModelSerializer):
class Meta:
model = Coffee
fields = '__all__'
Here is views for post request:
def addCoffee(request):
data = request.data
coffee = Coffee.objects.create(
name=data['name'],
ratings=data['ratings'],
taste=data['taste'],
coffeeType=data['coffeeType'],
price=data['price'],
img=data['img'],
shopName=data['shopName'],
coffeeShopID=data['coffeeShopID'],
location=data['location'],
user=data['user']
)
coffee.save()
serializer = CoffeeSerializers(coffee)
return Response(serializer.data)
i can only assume how your Account model looks like, problem is that you must send Account model, but you are sending string data['user']
def addCoffee(request):
data = request.data
account_object = Account.objects.get(THIS_IS_ACCOUNT_NAME = data['user'])
coffee = Coffee.objects.create(
name=data['name'],
ratings=data['ratings'],
taste=data['taste'],
coffeeType=data['coffeeType'],
price=data['price'],
img=data['img'],
shopName=data['shopName'],
coffeeShopID=data['coffeeShopID'],
location=data['location'],
user=account_object
)
coffee.save()
serializer = CoffeeSerializers(coffee)
return Response(serializer.data)

Having issue in handling multipart form data in django rest framework

I have an addproduct api in which frontend is sending a multipart/formdata in a post axios call. multipart/form-data is used because there is an image field that needs to be sent in arrays.
But I got the following error.
Category field is required
The data is sent like this
name: Soap
category[0]: 7
category[1]: 23
brand: 7
collection: 11
availability: in_stock
warranty: no_warranty
service: cash_on_delivery
rating: 3
best_seller: true
top_rated: true
featured: true
main_product_image: (binary)
merchant: 2
variants[0][product_id]: fgfdg
variants[0][price]: 127
variants[0][quantity]: 1
variants[0][color]: red
variants[0][size]: M
variants[0][variant_availability]: not_available
variants[0][variant_image]: (binary)
variants[1][product_id]: fgfdg
variants[1][price]: 127
variants[1][quantity]: 1
variants[1][color]: red
variants[1][size]: M
variants[1][variant_availability]: not_available
variants[1][variant_image]: (binary)
The same issue is with the variants.
My models:
class Variants(models.Model):
product_id = models.CharField(max_length=70, default='OAXWRTZ_12C',blank=True)
price = models.DecimalField(decimal_places=2, max_digits=20,default=500)
size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True)
color = models.CharField(max_length=70, default="not applicable",blank=True,null=True)
variant_image = models.ImageField(upload_to="products/images", blank=True,null=True)
thumbnail = ImageSpecField(source='variant_image',
processors=[ResizeToFill(100, 50)],
format='JPEG',
options={'quality': 60})
quantity = models.IntegerField(default=10,blank=True,null=True) # available quantity of given product
variant_availability = models.CharField(max_length=70, choices=AVAILABILITY, default='available')
class Meta:
verbose_name_plural = "Variants"
def __str__(self):
return self.product_id
#Product Model
class Product(models.Model):
merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True)
category = models.ManyToManyField(Category, blank=False)
sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
featured = models.BooleanField(default=False) # is product featured?
best_seller = models.BooleanField(default=False)
top_rated = models.BooleanField(default=False)
tags = TaggableManager(blank=True) # tags mechanism
name = models.CharField(max_length=150,unique=True)
main_product_image = models.ImageField(upload_to="products/images", null=True, blank=True)
thumbnail = ImageSpecField(source='main_product_image',
processors=[ResizeToFill(100, 50)],
format='JPEG',
options={'quality': 60})
slug = models.SlugField(max_length=200,blank=True)
description = RichTextField(blank=True)
#picture = models.ImageField(upload_to="products/images", null=True, blank=True)
picture = models.ManyToManyField(ImageBucket,null=True,blank=True,verbose_name="Add extra 3 images")
rating = models.IntegerField(choices=((1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 5))
)
availability = models.CharField(max_length=70, choices=AVAILABILITY, default='in_stock')
warranty = models.CharField(max_length=100, choices=WARRANTY, default='no_warranty')
services = models.CharField(max_length=100, choices=SERVICES, default='cash_on_delivery')
variants = models.ManyToManyField(Variants,related_name='products')
My view:
class ProductAddAPIView(CreateAPIView):
permission_classes = [IsAuthenticated]
parser_classes = [MultiPartParser,JSONParser,FormParser]
# queryset = Product.objects.all()
serializer_class = AddProductSerializer
Here I have used parser class just in case if it works.
Updated Code:
class AddProductSerializer(serializers.ModelSerializer):
id = serializers.PrimaryKeyRelatedField(read_only=True)
variants = VariantSerializer(many=True)
slug = serializers.SlugField(read_only=True)
class Meta:
model = Product
fields = ['id','merchant','featured', 'top_rated','category','brand','collection','sub_category',
'name','slug','description', 'main_product_image','best_seller','picture',
'rating','availability','warranty','services','variants']
#depth = 1
def create(self, validated_data):
#user = self.context['request'].user
picture_data = validated_data.get('picture')
merchant = validated_data.get('merchant')
category_data = validated_data.get('category')
featured = validated_data.get('featured')
top_rated = validated_data.get('top_rated')
brand = validated_data.get('brand')
collection = validated_data.get('collection')
sub_category = validated_data.get('sub_category')
name = validated_data.get('name')
description = validated_data.get('description')
main_product_image = validated_data.get('main_product_image')
best_seller = validated_data.get('best_seller')
rating = validated_data.get('rating')
availability = validated_data.get('availability')
warranty = validated_data.get('warranty')
services = validated_data.get('services')
#variants_logic
variants_data = validated_data.get('variants')
#breakpoint()
print(variants_data)
# from pudb import set_trace;set_trace()
#products-logic
product = Product.objects.create(featured=featured,top_rated=top_rated,
brand=brand,collection=collection,sub_category=sub_category,
name=name,description=description,
main_product_image=main_product_image,
best_seller=best_seller,rating=rating,
availability=availability,warranty=warranty,
services=services,merchant=merchant)
product.save()
product.category.set(category_data)
# product.variants.set(variants_data)
product.save()
for variants_data in variants_data:
abc = Variants.objects.create(**variants_data)
product.variants.add(abc)
product.save()
return product

Django custom queryset returns nothing

I am trying to write a year level filter for my student profile list, however, the query returns an empty [].
This is my Attendance model, manager and custom queryset:
class AttendanceQuerySet(models.QuerySet):
def get_yearlevel(self, yearlevel):
return self.filter(BCEID__YearLevel = yearlevel)
class AttendanceManager(models.Manager):
def get_queryset(self):
return AttendanceQuerySet(self.model, using=self._db)
def get_yearlevel(self, yearlevel):
return self.get_queryset().get_yearlevel(yearlevel)
class Attendance(models.Model):
BCEID = models.OneToOneField(StudentProfile,primary_key=True,on_delete=models.CASCADE)
AttendanceRate = models.CharField(max_length=10)
objects = AttendanceManager()
def __unicode__(self):
return self.BCEID
StudentProfile model:
class StudentProfile(models.Model):
RelatedPersonName = models.CharField(max_length=10)
RelatedPersonFirstName = models.CharField(max_length=30)
RelatedPersonFamName = models.CharField(max_length=30)
StudentLegalName = models.CharField(max_length=30)
StudentFamName = models.CharField(max_length=30)
Email = models.CharField(max_length=130)
Street1 = models.TextField(max_length=30)
Suburb = models.CharField(max_length=30)
State = models.CharField(max_length=5)
PostCode = models.CharField(max_length=6)
StudentLegalName = models.CharField(max_length=30)
StudentFamName = models.CharField(max_length=30)
StudentNo = models.CharField(primary_key=True,max_length=10)
Class = models.CharField(max_length=6)
YearLevel = models.CharField(max_length=10)
objects = StudentProfileManager()
def __unicode__(self):
return self.StudentNo
and AttendanceListView (views.py)
class AttendanceListView(ListView):
model = Attendance
queryset = Attendance.objects.get_yearlevel("Year 8")
I manually queried the database to check if there were errors in my code, and got the same result: an empty array [].
SQL:
SELECT "student_attendance"."BCEID_id",
"student_attendance"."AttendanceRate"
FROM "student_attendance"
INNER JOIN "student_studentprofile"
ON ("student_attendance"."BCEID_id" = "student_studentprofile"."StudentNo")
WHERE "student_studentprofile"."YearLevel" = 'Year 8'
Please let me know what I am doing wrong here.

get post by name of user or by id

i have this model
class Post(models.Model):
auth = models.ForeignKey(settings.AUTH_USER_MODEL,default=1)
title = models.CharField(max_length=120)
DESCSPECSOFT = (
(u'Null','Null'),
(u'Phone',u'Phone'),
(u'Car',u'Car'),
(u'Laptop',u'Laptop'),
(u'jops',u'Jops'),
(u'Electronic',u'Electronic'),
(u'Clothes',u'Clothes'),
(u'Makeup',u'Makeup'),
(u'Furnishings',u'Furnishings'),
(u'books',u'books'),
(u'sports',u'sports'),
(u'Property',u'Property'),
(u'Other',u'Other'),
)
City = (
(u'Null','Null'),
(u'Kosti',u'Kosti'),
(u'Khartoum',u'Khartoum'),
(u'Rabbik',u'Rabbik'),
(u'Duwaim',u'Duwaim'),
(u'Sinnar',u'Sinnar'),
(u'Bahri',u'Bahri'),
(u'Omdurman',u'Omdurman'),
(u'Sawakin',u'Sawakin'),
(u'Port Sudan',u'Port Sudan'),
(u'Kasala',u'Kasala'),
(u'Madani',u'Madani'),
(u'Alabid',u'Alabid'),
)
Case = (
(u'Null','Null'),
(u'New',u'New'),
(u'Old',u'Old'),
(u'Second Hand',u'Second Hand'),
(u'Other',u'Other'),
)
Type = models.CharField(choices=DESCSPECSOFT, default='Null',blank = False,null = False,max_length=120)
company = models.CharField(max_length=120)
dis = models.TextField(default="in here you w,ll write all the discribtion about your product")
image = models.ImageField(null=True,blank=True,width_field="width_field", height_field="height_field")
width_field = models.IntegerField(default=0)
height_field = models.IntegerField(default=0)
case = models.CharField(choices=Case, default=99,blank = False,null = False,max_length=120)
price = models.BigIntegerField(default=0)
city = models.CharField(choices=City, default='Null',blank = False,null = False,max_length=120)
address = models.CharField(max_length=120)
draft = models.BooleanField(default=False)
#pup = models.DateField(auto_now=False,auto_now_add=False ,null=False)
date = models.DateTimeField(auto_now=True ,auto_now_add=False)
puplis = models.DateTimeField(auto_now=False ,auto_now_add=True)
objects = PostManager()
def __str__(self):
return self.title
def __unicode__(self):
return self.title
any user can add a post but i want the user name show in the data base means the user how add the post because every post show the admin name not the user how add the post can someone show me haw can i fix this ???
sorry my en is bad ...