How to get specific key for manytomany and foreignkey - django

I have three models:
class Section(models.Model):
name = models.CharField()
class ParamText(models.Model):
text = models.TextField()
class Param(models.Model):
name = models.CharField()
value = models.IntegerField()
texts = models.ManyToManyField(ParamText)
section = models.ForeignField(Section)
This is simple example. Now I want to create class with concrete datas:
class ObjectTemplate(models.Model):
params = models.ManyToManyField(Param)
but I want put this model concrete ParamText in specyfic Param. My ObjectTemplate should contain many params[Param] (unique would be great) with only one selected ParamText for each Param.
How to realize this?

first of all to create a unique parmas[parm] use the OneToOneField instead of manytomany .
and to access a specific key : every object has an id so you can use that
let p be an Param's object
so to get the section id from the param you have to use
p.section.id
this would return a long int containing the id (primarykey) of the object.
I think the following will solve your one parmatext for each parma problem
class Section(models.Model):
name = models.CharField()
class ParamText(models.Model):
text = models.TextField()
class Param(models.Model):
name = models.CharField()
value = models.IntegerField()
texts = models.OneToOneField(ParamText)
section = models.ForeignField(Section)

Related

best way to create feature field for a product in Django

a Mobile device has many features in different types.
RAM=4: int
fingerprint=yes : boolean
camera=face detection, touch focus, panorama ...
how to create field for features, create an app for features and declare each feature type ? :
class IntFeature(models.Model):
title = models.CharField()
value = models.IntegerField()
class BoolFeature(models.Model):
title = models.CharField()
value = models.BooleanField()
class CharFeature(models.Model):
title = models.CharField()
value = models.CharField()
i guess all you need is just one class with an extra field which you'll define the type that you'll refer to it to cast the value
class Feature(models.Model):
title = models.CharField()
value = models.CharField() # it should be a string
type = models.CharField() # it could be an object, array, json, int, boolean ..
UPDATE
it seems you want to assign a bunch of attributes - values to a given product, may be you should look at woocommerce to get the idea or better Oscar a django-based ecommerce solution

How to inherit a model object instead of the model class

For some reasons, I want my Boolean Fields in my class Items(models.Model) to have a foreign key in my class ItemsGotten(models.Model). Here's my code for better understanding...
Items(models.Model):
title=models.Charfield(max_length=180)
description=models.Textfield(max_length=180)
paper=models.BooleanField(default=False, blank=True)
skin=models.BooleanField(default=False, blank=True)
ItemsGotten(models.Model):
user=models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
paperitem = models.ForeignKey(???)
skinitem = models.ForeignKey(???)```
I know that you can simply get the value of the whole model class e.g paperitem = models.ForeignKey(Items). But that's not what I want to achieve, I want to get only the object from the Items model. e.g skinitem = models.ForeignKey(Items.skin). Thanks

Django query complex query in one to one field model

I have two models of Student and Parent
Student models.py:
class StudentInfo(models.Model):
admissionNumber = models.BigIntegerField(primary_key=True,default=0)
firstName = models.CharField(max_length=20)
lastName = models.CharField(max_length=20)
fullName = models.CharField(max_length=50)
gender = models.CharField(max_length=20)
dob = models.DateField(null=True)
classSection = models.CharField(max_length=20)
Parent models.py
class ParentInfo(models.Model):
student = models.OneToOneField(StudentInfo,primary_key=True, on_delete=models.CASCADE)
fatherName = models.CharField(max_length=20)
motherName = models.CharField(max_length=20)
I have a form to search students through their fatherName.
So, what I want is to filter those students whose father's name contains 'some name'.
I tried this but it resultes in query set of ParentInfo:
parentInfo = ParentInfo.objects.all()
studentsInfo = parentInfo.filter(parent__fName = fName).select_related('student')
You should filter the opposite way, like:
StudentInfo.objects.filter(parentinfo__fatherName='name of father')
You here thus obtain a QuerySet of StudentInfos which contains zero, one, or more StudentInfos where there is a related ParentInfo object where the fatherName field is, in this case 'Name of father'.
Note: It might be better to implement a ForeignKey in the opposite order, such that multiple students can refer to the same ParentInfo object. Right now, a ParentInfo object can refer to exactly one StudentInfo. If there are students with the same parents (so siblings), then you introduce data duplication in the database.
# You can use contains attribute on the field of model and your query can be like this
student = models.ParentInfo.objects.values('student__firstName', 'student__lastName').filter(fatherName__contains='your value')
print(student[0]['student__firstName'])
print(student[0]['student__lastName'])

django custom model field

If I have 2 interlinked models:
class Person(models.Model)
name = models.CharField()
class Project(models.Model):
person = models.ForeignKey(Person)
title = models.CharField()
I frequently find myself trying to find the number of Projects associated with each Person:
person = Person.objects.get(id=1)
no_projects = Project.objects.filter(person=person).count()
Is there a way of adding this as a custom field to the Person model, such that I may just call person.no_projects?
This can be done by adding a property to the Person class.
class Person(models.Model)
name = models.CharField()
#property
def no_projects(self):
return Project.objects.filter(person=self).count()
This can be called now like this
person = Person.objects.get(id=1)
person.no_projects
In fact, that functionality is (almost) built-in. Instead of querying Projects, you can just do person.project_set.count() to get that person's count of projects (and .all() to get the actual list).
You can use the property() to generate the dynamical field.
class Project(models.Model):
person = models.ForeignKey(Person)
title = models.CharField()
def _get_no_projects(self):
return Projects.objects.filter(person=self).count()
no_projects = property(_get_no_projects)
But the dynamical fields can not be used in querying, because the they don't really store data into the database.
FYI: http://www.b-list.org/weblog/2006/aug/18/django-tips-using-properties-models-and-managers/

Model (Product) attributes used in product, alert, predefined search.. is it right with DRY concept?

First of all I would like to mention that I am not an experienced programmer.
Say there's a model Product, and there are some types of products with different attributes (well, 2 types for example).
I have one BaseProduct model with User, creation_date, creation_ip and some more attributes and subclassed child models with specified for this type of product attributes.
Class BaseProduct(models.Model):
name = models.CharField()
type = models.CharField()
creation_date = models.DateField()
creation_ip = models.IpAddressfield()
class ProductTypeX(BaseProduct):
attribute_1 = models.ForeignKey(some_other_model)
attribute_2 = models.ForeignKey(some_other_model2)
class ProductTypeY(BaseProduct):
attribute_1 = models.ForeignKey(some_other_model)
attribute_2 = models.ForeignKey(some_other_model2)
There's an option creating email alert on creation of new product based on some criteria, and there's also a "quick predefined search" based on some criteria too. For these I've created (again...) models.
class BaseAlert(models.Model):
name = models.CharField()
email = models.BooleanField()
sms = models.BooleanField()
ProductTypeXAlert(BaseAlert):
attribute_1 = models.ForeignKey(some_other_model)
attribute_2 = models.ForeignKey(some_other_model2)
ProductTypeYAlert(BaseAlert):
attribute_1 = models.ForeignKey(some_other_model1)
attribute_2 = models.ForeignKey(some_other_model2)
class BasePredefinedSearch(models.Model):
name = models.CharField()
ProductTypeXPredefinedSearch(BasePredefinedSearch):
attribute_1 = models.ForeignKey(some_other_model1)
Is this the right solution or should I create some universal Attribute model for alert, predefinedsearch ??.. I am repeating attributes fields here many times. What is your opinion on that ?
Thanks
I would make an AttributesBase abstract model and use multiple inheritance:
class AttributesBase(models.Model):
class Meta:
abstract = True
attribute1 = models.ForeignKey(SomeOtherModel1)
attribute2 = models.ForeignKey(SomeOtherModel2)
class ProductTypeX(BaseProduct, AttributesBase):
"""Defines product type X"""
Hope that helps you out.