How can we create a model record or object using another object.
get_object = my_model.objects.filter(id=1)
I want to do something like below to create object in another database
my_model.objects.using('DB2').create(my_model=get_object)
You can overide save method or use django signals, based on your requirements.
You can use the code below to replicate the object to the model in another database having same fields.
get_object = my_model.objects.filter(id=1).values().first()
get_object.update({'id': None})
my_model.objects.using('DB2').create(**get_object)
You can get yours model as dict and unpack it to new model object.
from users.models import User, AnotherUser
from django.forms.models import model_to_dict
old_user = User.objects.get(pk=1)
data = model_to_dict(old_user, fields=['username', 'email'])
new_user = AnotherUser.objects.using('DB2').create(**data)
Its better to not copy pk(id) but provide this to database by itself
Related
I am using django-filter v1.1.0 , django 1.11. I want a dynamic filter for a model. I have created filters.py which contains the respective config for model filters. This site tells that:
It will generate a Django Form with the search fields as well as
return the filtered QuerySet.
It here refers to SomeModelFilter function. I tried applying len and objects functions to it's object, but it returns
AttributeError: 'SomeModelFilter' object has no attribute 'len'
AttributeError: 'SomeModelFilter' object has no attribute 'objects'
I want to get the filtered content. It doesn't seem to be a QuerySet to me.
filters.py
from project_app.models import *
import django_filters
class SomeModelFilter(django_filters.FilterSet):
class Meta:
model = SomeModel
fields = ['field_a', 'field_b', 'field_c', 'field_d']
views.py
somemodel_list = SomeModel.objects.all()
somemodel_filter = SomeModelFilter(request.GET, queryset=somemodel_list)
print(len(somemodel_filter)) # This gives the first error
print(somemodel_filter.objects.all()) # This gives the second error
I want to get the filtered content, hopefully which is contained in somemodel_filter object.
The problem is in this line print(somemodel_filter.objects.all()). somemodel_filter is not model, it's filterset instance and since it's don't have objects attribute. To get filtered queryset use qs attribute, like this:
print(somemodel_filter.qs)
You can find example of filter usage here.
filtered_data = ExampleFilter(requet.Get, queryset=Example.objects.all())
to get the filtered queryset
filtered_queryset_data = filtered_data.qs
Use serializer to serialize the data. Use many=true since the its a list
serialized_data = ExampleSerializer(filtered_queryset_data, many=true).data
I've successfully used Graphene-Django to successfully build several GraphQL calls. In all of those cases I populated, in whole or in part, a Django model and then returned the records I populated.
Now I have a situation where I'd like to return some data that I don't wish to store in the Django model. Is this possible to do with Graphene?
Robert
Robert_LY answered his own question perfectly in the comments, I'd just like to expand his solution.
My database-less model WordForm is generated automatically, without storing it in a database. I define it as a Django model as follows:
from django.db import models
class WordForm(models.Model):
value = models.CharField(max_length=100)
attributes = models.CharField(max_length=100)
In the schema I define the node and query like this:
class WordFormNode(DjangoObjectType):
class Meta:
model = WordForm
interfaces = (relay.Node, )
class Query(AbstractType):
word_forms = List(WordFormNode,query=String(),some_id=String())
def resolve_word_forms(self, args, context, info):
query= args['query']
some_id = from_global_id(args['some_id'])[1]
word_forms = []
# some logic to make WordForm objects with
# WordForm(value=value,attributes=attributes),
# then append them to list word_forms
return word_forms
You can pass as many arguments as you like to the List and access them in resolve_word_forms.
When you map your Django model to a GraphQL, it create a new model with GraphQL object types from the introspection of the Django model..
And nothing prevent you to combine this model with with plain GraphQL objects types, or mapped from an other third party persistence model
This is my model in Django.
class Meta_Columns(models.Model):
cur_parent=models.CharField(max_length=200)
cur_child=models.CharField(max_length=200)
cur_child_label=models.CharField(max_length=200)
cur_childisparent= models.BooleanField()
cur_childtype= models.CharField(max_length=200,choices=CHILD_TYPE)
cur_Misc= models.CharField(max_length=200,blank=True)
class Admin:
pass
I want to select the 'cur_parent' column and get the distinct values (from MySql)
Below is the code.
if request.method == 'POST':
all_parents = Meta_Columns.objects.only("cur_parent").distinct("cur_parent")
data = serializers.serialize("json", all_parents)
return HttpResponse(data, content_type='application/json')
If i make the call to the view, this is the error i get.
DISTINCT ON fields is not supported by this database backend
I cannot use values("field_name").distinct() because it will not work with json & this error is thrown : 'dict' object has no attribute '_meta'.
How to get distinct values then?
Django's serializers.serialize() expects Django model instances as inputs, and distinct() won't be returning that (even more so because cur_parent is not a ref to a model, but a CharField)
If .values('cur_parent') works for you, you can just serialize that list of distinct parents with a regular JSON serializer, e.g.
import json
all_parents = Meta_Columns.objects....values('cur_parent').distinct()
json_str = json.dumps(all_parents) # Works with regular data structure,
# doesn't need to be a Django model instance
return HttpResponse(json_str, content_type='application/json')
In variable called object_type I store values like: Profile or Company which are names of models available in the app. Both models has field called uuid.
I need to something like this:
get_object_or_404(object_type, uuid=uuid_from_request)
how can I pass object_type value (Profile or Company) to query correct model?
How about using a dictionary that map model names to model classes:
object_types = {'Profile': Profile, 'Company': Compnay}
...
get_object_or_404(object_types[object_type], uuid=uuid_from_request)
Or using getattr:
import app.models
get_object_or_404(getattr(app.model, object_type), uuid=uuid_from_request)
In django all model types are stored in magical cache, so you might use this cache to get model types, like that:
from django.db.models.loading import get_model
Model = get_model("your_app_name", "Profile")
get_object_or_404(object_type, uuid=uuid_from_request)
I have following model:
class ProjectBudget(models.Model):
It has a form and inline:
class ProjectBudgetAdmin(admin.ModelAdmin):
form = ProjectBudgetForm
inlines= [ProjectSpentsInline]
class ProjectSpentsInline(admin.TabularInline):
model = ProjectSpents
On a form i have a field file. From this file i want populate inline object ProjectSpents values:
class ProjectBudgetForm(ModelForm):
file = forms.FileField
def clean_file(self):
parse file then populate inline model objects ProjectSpents....
The problem is that i want to edit inline values of ProjectSpents from clean_file, but there is a problem, because queryset is already fullfilled before clean_file and new inline values are not
shoiwing. Maybe there is another solution?
Try overriding the model admin method save_formset. You can iterate through the formset instances to delete the existing inlines, then access form.cleaned_data['file'] and create the new related instances.