I'm setting up a django project, I have 2 existing models Offers and Candidates, what I want to do is to create a new model (Scoring model) based on the two models Offers and Candidates, so i created a function add_line() in my Offer model that should create the Scoring object but it wont work even when I used the post_save signal, any suggestion?
Candidates model:
class Candidates(models.Model):
nom = models.CharField(max_length = 50)
prenom = models.CharField(max_length= 50)
email = models.EmailField()
phone = models.CharField(max_length=100)
niveau_d_experience = models.IntegerField()
etablissement_universitaire= models.CharField(max_length=150)
niveau_options = (('Licence', 'Licence'), ('Master', 'Master'), ("Diplôme d'ingénieur", "Diplôme d'ingénieur"), ('Doctorat', 'Doctorat'))
niveau_educatif = models.CharField(choices=niveau_options, max_length=100)
profil = models.CharField(max_length=100)
sexe_options = (('Mâle', 'Mâle'), ('Femelle', 'Femelle'))
sexe = models.CharField(choices=sexe_options, max_length=100)
offre = models.CharField(max_length= 200)
CV = models.FileField()
date_creation = models.DateTimeField(auto_now_add=True, auto_now=False)
text_resume = models.TextField(editable=False)
language = models.CharField(max_length = 20, editable=False)
Offers model:
class Offers(models.Model):
titre = models.CharField(max_length=120)
description = models.TextField()
technologies = models.TextField()
softskills = models.TextField()
expérience = models.IntegerField()
contrat_options= (('CDI', 'CDI'), ('CDD', 'CDD'), ('Freelance', 'Freelance'), ('Stage', 'Stage'))
contrat = models.CharField(choices=contrat_options, max_length=100)
mission_options = (('Interne', 'Interne'), ('Externe', 'Externe'))
mission= models.CharField(choices=mission_options, max_length=100)
validation_options = (('Offre validée', 'Offre validée'), ('Offre pourvue', 'Offre pourvue'))
validation = models.CharField(choices =validation_options, max_length=100)
def add_line(self, **kwargs):
queryset = Candidates.objects.all()
for candidate in queryset:
scoring, created = Scoring.objects.get_or_create(
offer_id = self,
cand_id = candidate
)
return scoring
def __str__(self):
return self.titre
and Scoring model:
class Scoring(models.Model):
offer_id = models.ForeignKey(Offers, on_delete = models.DO_NOTHING, editable = False)
cand_id = models.ForeignKey(Candidates, on_delete = models.DO_NOTHING, editable= False)
Related
I have a Warehouse model like the following:
class ShelfBin(models.Model):
bin_id = models.IntegerField(default=0)
bin_name = models.CharField(max_length=50, default=0)
class UnitShelf(models.Model):
shelf_id = models.IntegerField(default=0)
shelf_name = models.CharField(max_length=50, default=0)
bin = models.ManyToManyField(ShelfBin, blank=True)
class AisleUnit(models.Model):
unit_id = models.IntegerField(default=0)
unit_name = models.CharField(max_length=50, default=0)
shelf = models.ManyToManyField(UnitShelf, blank=True)
class ZoneAisle(models.Model):
aisle_id = models.IntegerField(default=0)
aisle_name = models.CharField(max_length=50, default=0)
unit = models.ManyToManyField(AisleUnit, blank=True)
class WarehouseZone(models.Model):
zone_id = models.IntegerField(default=0)
zone_name = models.CharField(max_length=50, default=0)
aisle = models.ManyToManyField(ZoneAisle, blank=True)
class Warehouse(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=250, default=0)
address = models.CharField(max_length=500, default=0)
zones = models.ManyToManyField(WarehouseZone, blank=True)
for this I have created a serializer like the following:
class WarehouseSerializer(serializers.ModelSerializer):
zones = WarehouseZonesSerializer(many=True)
class Meta:
model = Warehouse
fields = "__all__"
def create(self, validated_data):
print("validated data warehouse", validated_data)
zone_objects = validated_data.pop('zones', None)
instance = Warehouse.objects.create(**validated_data)
for item in zone_objects:
aisle_objects = item.pop('aisle')
wz_obj = WarehouseZone.objects.create(**item)
for data in aisle_objects:
unit_objects = data.pop('unit')
za_obj = ZoneAisle.objects.create(**data)
for u_data in unit_objects:
shelf_objects = u_data.pop('shelf')
au_obj = AisleUnit.objects.create(**u_data)
for s_data in shelf_objects:
bin_objects = s_data.pop('bin')
us_obj = UnitShelf.objects.create(**s_data)
for b_data in bin_objects:
b_obj = ShelfBin.objects.create(**b_data)
us_obj.bin.add(b_obj)
au_obj.shelf.add(us_obj)
za_obj.unit.add(au_obj)
wz_obj.aisle.add(za_obj)
instance.zones.add(wz_obj)
return instance
Now the problem is that sometimes warehouse can have zone, aisle, units, etc(all 5 sub-levels) but sometimes it can only be 1,2 or 0 level deep
and in that cases it raises error like this :
aisle_objects = item.pop('aisle')
KeyError: 'aisle'
So do I have to use try and except at each level of the loop or is there a better way to handle these exceptions?
class ProductSerizer(serializers.ModelSerializer):
category = serializers.PrimaryKeyRelatedField(queryset=Category.objects)
title_of_product = serializers.CharField(required=True)
slug = serializers.SlugField(required=True)
image_of_product = serializers.ImageField(required=True)
description_of_product = serializers.CharField(required=True)
price_of_product = serializers.DecimalField(max_digits=12, decimal_places=2, required=True)
class Product(models.Model):
class Meta:
abstract = True
category = models.ForeignKey(Category, verbose_name="category", on_delete=models.CASCADE)
title_of_product = models.CharField(max_length=225,verbose_name="Title",null=True)
slug = models.SlugField(unique=True)
image_of_product = models.ImageField(verbose_name="Image", null=True)
description_of_product = models.TextField(verbose_name = "Descripwtion", null = True)
price_of_product = models.DecimalField(max_digits=10,decimal_places=2, verbose_name="Price", null=True)
and I want to list all elements from categories, but I cannot serialize this class. How should I do ?
Take a look at this thread, which talks about abtract models and how to serialize them
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() ]
Good day.
Am having a model called AddInv
AddInv(models.Model):
client = models.ForeignKey(User, null=True)
description = models.CharField(max_length = 100)
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.PositiveIntegerField()
sold = models.PositiveIntegerField(default=0)
details = models.CharField(max_length = 100)
country = models.ForeignKey(Signup, null = True)
def __str__(self):
return self.country
Model for Signup is
class Signup(models.Model):
user = models.OneToOneField(User)
phone_number = models.PositiveIntegerField( null=True)
zipcode = models.PositiveIntegerField(null=True)
street = models.CharField(max_length = 75, null=True)
city = models.CharField(max_length = 75, null=True)
state = models.CharField(max_length = 75, null= True)
country = models.CharField(max_length = 32, null=True, choices = CATEGORIES)
def __str__(self):
return self.country
and a views to filter by country
def homepage(request): # Client View
context = {}
items = get_object_or_404(AddInv, country="USA")
print "Items", items
return render(request, "selly/homepage.html", {'items': items})
Am having error pointing to
items = get_object_or_404(AddInv, country="USA")
What could be wrong with the code
Try this. Just an assume
items = get_object_or_404(AddInv, country__country="USA")
I used
items = AddInv.objects.filter(country__country="USA")
which worked
How can I get the foreign key values? I have a common vehicle model that links to the year, series, engine type, body style, transmission and drive train...all as foreign keys. I'd like to get the values of these fields for my app, but I'm stuck as to how I'd go about them. Any ideas will be highly appreciated.
class Model(models.Model):
model = models.CharField(max_length=15, blank=False)
manufacturer = models.ForeignKey(Manufacturer)
date_added = models.DateField()
def __unicode__(self):
name = ''+str(self.manufacturer)+" "+str(self.model)
return name
class Year(models.Model):
ALPHA_NUMERIC_CHOICES = (
('1', 'Numeric'),
('A', 'Alphabetic'),
)
year = models.PositiveSmallIntegerField()
position_7_char = models.CharField(max_length=1, choices=ALPHA_NUMERIC_CHOICES)
position_10 = models.CharField(max_length=1, blank=False)
def __unicode__(self):
return unicode(self.year)
class Series(models.Model):
series = models.CharField(max_length=20, blank=True)
model = models.ForeignKey(Model)
date_added = models.DateField()
def __unicode__(self):
name = str(self.model)+" "+str(self.series)
return name
class CommonVehicle(models.Model):
year = models.ForeignKey(Year)
series = models.ForeignKey(Series)
engine = models.ForeignKey(Engine)
body_style = models.ForeignKey(BodyStyle)
transmission = models.ForeignKey(Transmission)
drive_train = models.ForeignKey(DriveTrain)
def __unicode__(self):
name = ''+str(self.year)+" "+str(self.series)
return name
class Vehicle(models.Model):
stock_number = models.CharField(max_length=6, blank=False)
vin = models.CharField(max_length=17, blank=False)
common_vehicle = models.ForeignKey(CommonVehicle)
exterior_colour = models.ForeignKey(ExteriorColour)
interior_colour = models.ForeignKey(InteriorColour)
interior_type = models.ForeignKey(InteriorType)
odometer_unit = models.ForeignKey(OdometerUnit)
status = models.ForeignKey(Status)
odometer_reading = models.PositiveIntegerField()
selling_price = models.PositiveIntegerField()
purchase_date = models.DateField()
sales_description = models.CharField(max_length=60, blank=False)
def __unicode__(self):
return self.stock_numberodels.ForeignKey(CommonVehicle)
You need the actual IDs? Try something like my_vehicle_ref.series.id.
Also, I hope you know that the series attribute right there is really an instance of Series, so you could access any of it's properties, e.g., my_vehicle_ref.series.model.model.