django queryset ..search objects from one field of a model to another field of the other model - django-queryset

I have to build a queryset in which we can select all the objects from a field in a model and compare to the field in another model...
For Eg:- i have to select all the objects in docid field with corresponding amount from profitandloss model and compare to docid with corresponding amount from balancesheet model
Model -1
Class Profitandloss(models.Model):
docid = models.charfield(max_length=15)
amount = models.integerfield(default=0)
class balancesheet(models.Model):
docid = models.charfield(max_length=15)
amount = models.integerfield(default=0)

Your model design needs changing. you should have document as another model and link document model to your profileandloss and balancesheet model as foriegnkey This will allow ORM search effectively

Related

How to save partial data in a separate model and then query checks if that data exists?

My data consists of some products, which are defined in FdProduct model:
# models.py:
class FdProduct(models.Model):
product_id = models.CharField(max_length=10, primary_key=True)
name = models.CharField(max_length=40)
active = models.BooleanField(default=True)
def __str__(self):
return self.product_id
# serializers.py:
class FdProductSerializer(serializers.ModelSerializer):
product_id = serializers.RegexField(regex='^\d{3}\.\d{6}$', max_length=10, min_length=10, allow_blank=False)
name = serializers.CharField(min_length=6, max_length=50, allow_blank=False)
class Meta:
model = FdProduct
fields = '__all__'
For each existing product I can prepare a configuration and save it using a model called SavedConfiguration:
# models:
class SavedConfiguration(models.Model):
saved_conf_id = models.CharField(max_length=13, primary_key=True)
saved_config = models.TextField()
product = models.ForeignKey(FdProduct, on_delete=models.CASCADE, default=0)
session_id = models.CharField(max_length=40, default=0)
creation_date = models.DateTimeField(auto_now=False, auto_now_add=True)
def __str__(self):
return str(self.saved_conf_id)
# serializers.py:
class SavedConfigurationSerializer(serializers.ModelSerializer):
saved_conf_id = serializers.RegexField(regex='^sc\d{2}', allow_blank=False)
saved_config = serializers.CharField(min_length=6)
session_id = serializers.RegexField(regex='^se\d{2}', allow_blank=False)
class Meta:
model = SavedConfiguration
fields = '__all__'
By connecting the SavedConfiguration with FdProduct model with use of ForeignKey I ensure that a product exists in the database when I configure it and want to save the configuration.
I'd like to introduce two things more: the first one would be a model for storing just a product_id and an array containing all saved_conf_ids for that product:
# models.py:
class ConfigOptions(models.Model):
product_id = ...
saved_conf_id = [...]
For example, if I configured a couple of times two products, Product One and Product Three, I may have data like this:
- Product One:
- C_ID_0023
- C_ID_0025
- C_ID_0032
- Product Three:
- C_ID_0149
- C_ID_0273
My question now is, how to construct such model and serializer for which records are created (copied) into ConfigOptions model table each time SavedConfiguration is saved?
Second question: I'm thinking about creating another model, say ConfigPresenceCheck, which would receive POST requests and based on that would check if saved product configurations exist (so, fetching them from ConfigOptions or returning 404), and if they exist, would return them together with all parameters from SavedConfiguration (e.g. saved_config, session_id, etc.).
Please give me directions how to build such models. I'd also appreciate some good tutorials related to
constructing Django models.
I think you should use many to many fields instead of foreign key, from my understanding many products can have many saved configurations and vice versa, at database level many to many fields are stored by creating a table any way.

How to post data to Embedded document with Mongoengine REST

I am trying to use Django with mongoengine to make an API.
So far I can get the objects and delete them. but when I want to post some data. Lets say student + course it is giving an error:
type object 'Course' has no attribute 'objects'
Models en ..
#Model.py
class Course(EmbeddedDocument):
course_name = StringField(max_length=200)
course_fee = StringField(max_length=200)
class Student(Document):
student_name = StringField(max_length=200)
student_contactperson = StringField(max_length=200)
student_adress = StringField(max_length=200)
courses = ListField(EmbeddedDocumentField(Course))
#Serializers.py
class CourseSerializer(EmbeddedDocumentSerializer):
class Meta:
model = Course
fields = ('course_name','course_fee')
class StudentSerializer(DocumentSerializer):
courses = CourseSerializer(many=True)
class Meta:
model = Student
fields = ('student_name','student_contactperson','student_adress','courses')
depth = 2
def create(self, validated_data):
course_data = validated_data.pop('courses')
student = Student.objects.create(**validated_data)
Course.objects.create(student=student, **course_data)
return student
#Views.py
class StudentViewSet(meviewsets.ModelViewSet):
lookup_field = 'name'
queryset = Student.objects.all().order_by('-date_joined')
serializer_class = StudentSerializer
A Document represents a MongoDB document (i.e a record in a collection), a Document class is bound to a particular collection. An EmbeddedDocument represents a structure that gets nested in a Document.
So by design an EmbeddedDocument isn't attached to any collection unless you embed it inside a Document.
This means that you can't query or save an EmbeddedDocument class, you need to query/save the parent Document.
Document.objects is an entry point for querying a collection, it only exists on Document classes. You are calling Course.objects.create but Course is an EmbeddedDocument.
I believe you need to change your code to the following
class StudentSerializer(DocumentSerializer):
...
def create(self, validated_data):
course_data = validated_data.pop('courses')
course = Course(**course_data) # assuming course_data is {course_name: ..., course_fee: ...}
return Student.objects.create(courses=[course], **validated_data)

Laravel 4 finding collection based on relationship with 2 other models

I have models like this:
have a table (product_types) of product types.
have a table (products) of products with a many-to-one relationships to the product types table.
have a table (attribute_types) of attribute types.
have a table of (many-to-many) relationships between product types and attribute types
have a table (attributes) containing attribute type, attribute value.
have a table of (many-to-many) relationships between products and attributes.
There are a few main things I need to do with this collection
$product_type = ProductType::find(1);
Find all the products for a product type.
return $product_type->products;
Find all the attribute types for a product type
return $product_type->attribute_types;
Find all the attributes for the attribute type and product type. I know the problem here is I need attributes to be the children of product type and attribute type.
But, I'm not sure the best way to do this.
Setup relations like in docs http://laravel.com/docs/eloquent#relationships
Then you can get collection you want like this:
//return $product_type->products;
$product_type->load('products')->products; // returns Eloquent Collection of products
// or shorter equivalent:
$product_type->products;
//return $product_type->attribute_types;
the same as above since the relationships are identical (many-to-many)
// Then to get Attributes:
$product_type->load('products.attributes');
//then you can get all attributes as a single array (every attr as an array not model):
$attributesArray = $product_type->products->fetch('attributes')->collapse();
// or without casting merge all Attributes in a loop:
$attributesCollection = new \Illuminate\Database\Eloquent\Collection;
foreach ($product_type->products as $product)
{
$attributesCollection = $attributesCollection->merge($product->attributes);
}

Django Rest Framework - Exclude field from related object

I have two related models and serializers for both of them. When I am serializing one of these models (the serializer has a depth of 1) the result includes some fields from the related object that should't be visible. How an I specify which serializer to use for the relation? Or is there anyway to tell Rest Framework to exclude some fields from the related object?
Thank you,
I think one way would be to create an extra serializer for the model where you want to return only limited number of fields and then use this serializer in the serializer of the other model. Something like this:
class MyModelSerializerLimited(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ('field1', 'field2') #fields that you want to display
Then in the other serializer use the MyModelSerializerLimited:
class OtherModelSerializer(serializers.ModelSerializer):
myfield = MyModelSerializerLimited()
class Meta:
model = OtherModel
fields = ('myfield', ...)
depth = 1
You could override restore_fields method on serializer. Here in restore_fields method you can modify list of fields - serializer.fields - pop, push or modify any of the fields.
eg: Field workspace is read_only when action is not 'create'
class MyPostSerializer(ModelSerializer):
def restore_fields(self, data, files):
if (self.context.get('view').action != 'create'):
self.fields.get('workspace').read_only=True
return super(MyPostSerializer, self).restore_fields(data, files)
class Meta:
model = MyPost
fields = ('id', 'name', 'workspace')

Django ModelForms: Trying to save a form using a foreign key ID

I'm trying to create a new Topic and the category id is dynamically determined in javascript on the client side. The problem i'm having is I pass the category id and I want to lookup the correct category object, but using a model form, it checks if the category is an instance of Category before I can assign it and save it.
--model.py--
class Topic(models.Model):
category = models.ForeignKey(Category)
--form.py--
class TopicForm(ModelForm):
category = forms.IntegerField(widget=forms.HiddenInput())
class Meta:
model = Topic
fields = ('category')
--view.py--
form = TopicForm(request.POST)
if form.is_valid():
form.save(commit=False) # throws exception category is not a Category instance
form.category = Category.objects.get(pk=form.cleaned_data.get('category'))
form.save()
Use a ModelChoiceField instead of the IntegerField in your form. See the built-in fields reference
Following Oggy's suggestion, I changed it to a ModelChoiceField and now Django does all the magic behind the scenes.
category = forms.ModelChoiceField(Category.objects.all(), widget=forms.HiddenInput())
Now I hope the queryset doesn't get evaluated, since it's not necessary and there are 90,000 records. :)

Resources