I am using mongoengine with Django
Below is my Model class
class MyLocation(EmbeddedDocument):
my_id = IntField(required=True)
lat = GeoPointField(required=False)
updated_date_time = DateTimeField(default=datetime.datetime.utcnow)
My Views.py
def store_my_location():
loc = MyLocation(1, [30.8993487, -74.0145665])
loc.save()
When I am calling the above method I getting error AttributeError: _auto_id_field
Please suggest a solution
I suggest using the names when you save the location. Since class definition does not include how you put in these keys that is why we need to use the name to define them.
def store_my_location():
loc = MyLocation(my_id=1, lat=[30.8993487, -74.0145665])
loc.save()
This should work.
One more appraoch is to write everything in MyLocation class.
class MyLocation(EmbeddedDocument):
my_id = IntField(required=True)
lat = GeoPointField(required=False)
updated_date_time = DateTimeField(default=datetime.datetime.utcnow)
def create(my_id,lat):
location=MyLocation(my_id=my_id,lat=lat)
location.save()
return location
def store_my_location():
loc = MyLocation.create(1,[30.8993487, -74.0145665])
Related
I am getting empty in return (from my model methods), I don't get where I am wrong in this, we can query model using self
class SocialLinks(models.Model):
alias_name = models.CharField(max_length=10,)
name = models.CharField(max_length=30)
url_link = models.URLField()
def get_fb_link(self):
try:
fb = self.objects.get(alias_name='fb')
return fb.url_link
except:
return ""
def get_linkdin_link(self):
try:
linkdin = self.objects.get(alias_name='linkedin')
return linkdin
except:
return ""
def get_insta_link(self):
try:
insta = self.objects.get(alias_name='insta')
return insta.url_link
except:
Your issue is that self corresponds to one instance of the model class, not the class itself.
So you can do
all_fb_links = SocialLinks.objects.filter(alias_name="fb")
and you will get all the records from the model that are facebook links, but you cannot do this referencing a single instance of the record using self.
You could write a class method, but what you actually want here is a model manager to define some specific queries so that you can then do
SocialLinks.get_all_fb_links()
Here's the docs on defining a custom manager: https://docs.djangoproject.com/en/3.2/topics/db/managers/
A method on the class like you are defining would be used to return something not stored on the table, but which could perhaps be derived from it. A simple example might be:
def link_type_and_url(self):
return f"{self.alias_name}:{url_link}"
views.py
def passAuthProjFeature(request):
if request.method == 'POST':
author_name = request.POST['author_id']
project_id = request.POST['tcgproject_id']
feature_name = request.POST['tcgsearch_id']
project_name =Project.objects.filter(id=project_id)
project_name=str(project_name)
project_name = project_name.split[" "][1]
project_name = project_name.split[">"][0]
when i print project name it gives me in []
I want only projectname in variable
You get instance of Project class, but it seems that you need only one field of instance, for example 'name'. You can get this:
project = Project.objects.values('name').get(id=project_id)
project_name = project['name']
project_name =Project.objects.filter(id=project_id)
As you are using filter() method in the ORM query, it is returning the list of project objects.
I think better is to use the get() method in the query to get the desired result.
Assuming the below the model structure:
class Project(models.Model):
name = models.CharField(max_length=any numeric value)
......
Try this query:
project_name = Project.objects.get(id=project_id).name
My question is about creating a QuerySet Mixin which provides identical QuerySet methods for both a model and a related model. Here is example code, and the first class ByPositionMixin is what I am focused on:
from django.db import models
from django.db.models.query import QuerySet
from django.core.exceptions import FieldError
class ByPositionMixin(object):
def batters(self):
try:
return self.exclude(positions=1)
except FieldError:
return self.exclude(position=1)
class PlayerQuerySet(QuerySet, ByPositionMixin):
pass
class PlayerPositionQuerySet(QuerySet, ByPositionMixin):
pass
class PlayerManager(models.Manager):
def get_query_set(self):
return PlayerQuerySet(self.model, using=self._db)
class PlayerPositionManager(models.Manager):
def get_query_set(self):
return PlayerPositionQuerySet(self.model, using=self._db)
class Position(models.Model):
# pos_list in order ('P', 'C', '1B', '2B', '3B', 'SS', 'LF', 'CF', 'RF')
# pos id / pk correspond to index value of pos_list(pos)
pos = models.CharField(max_length=2)
class Player(models.Model):
name = models.CharField(max_length=100)
positions = models.ManyToManyField(Position, through='PlayerPosition')
objects = PlayerManager()
class PlayerPosition(models.Model):
player = models.ForeignKey(Player)
position = models.ForeignKey(Position)
primary = models.BooleanField()
objects = PlayerPositionManager()
Inside ByPositionMixin, I try exclude(positions=1) which queries against PlayerQuerySet and if that generates a FieldError, I try exclude(position=1) which queries against PlayerPositionQuerySet. The difference in field names is precise, a Player() has positions, but a PlayerPosition() has only one position. So the difference it the exclude() query is 'positions' / 'position'. Since I will have many custom queries (e.g. batters(), pitchers(), by_position() etc.), do I have to write out try / except code for each one?
Or is there a different approach which would let me write custom queries without having to try against one model and then against the other one?
UPDATE: basically, I have decided to write a kwarg helper function, which provides the correct kwargs for both Player and PlayerPosition. It's a little elaborate (and perhaps completely unnecessary), but should be able to be made to simplify the code for several custom queries.
class ByPositionMixin(object):
def pkw(self, **kwargs):
# returns appropriate kwargs, at the moment, only handles one kwarg
key = kwargs.keys()[0] # e.g. 'positions__in'
value = kwargs[key]
key_args = key.split('__')
if self.model.__name__ == 'Player':
first_arg = 'positions'
elif self.model.__name__ == 'PlayerPosition':
first_arg = 'position'
else:
first_arg = key_args[0]
key = '__'.join([first_arg] + key_args[1:])
return {key: value}
def batters(self): # shows how pkw() is used
return self.exclude(**self.pkw(positions=1))
I'm working on a backend for an app and writing a function to retrieve data from several tables and then construct a httpresponse from that.
What I would like to do is get a vaccine, then all the diseases for that vaccine and then construct something(object, list, dict, ...) containing everything.
What I've got so far is:
def vaccinepack(request, country_id):
vaccines = Vaccine.objects.filter(diseases__countries__id=country_id)
diseases = []
json = serializers.get_serializer("json")()
response = HttpResponse()
for v in vaccines:
dis = Disease.objects.filter(vaccine=v.id)
disdata = ""
for d in dis:
disdata += json.serialize([d], ensure_ascii=False)
json.serialize([v, disdata], ensure_ascii=False, stream=response)
return response
But I'm running to trouble when serialising [v, disdata].
'list' object has no attribute '_meta'.
I'm rather new to Django so I'm not sure what's the proper way of doing this.
Here's my models:
class Disease(models.Model):
name = models.CharField(max_length=100)
text = models.CharField(max_length=2000)
countries = models.ManyToManyField(Country, blank=True)
def __unicode__(self):
return self.name
class Vaccine(models.Model):
name = models.CharField(max_length=100)
text = models.CharField(max_length=2000)
diseases = models.ManyToManyField(Disease, blank=True)
def __unicode__(self):
return self.name
The immediate cause of your error message is because you're passing a list object to the Django serializer, but it's expecting a QuerySet.
What I would do is to build up the data structure as a series of nested Python dictionaries, and then convert it all to JSON at the end with json.dumps(). (Note that's the actual built-in json library, which you've shadowed with the serializer.) Something like (untested):
serializer = serializers.get_serializer('python')
vaccine_list = serializer.serialize(vaccines)
for i, v in enumerate(vaccines):
diseases = v.diseases.all()
disease_list = serializer.serialize(diseases)
vaccine_list[i]['fields']['diseases'] = disease_list
data = json.dumps(vaccine_list)
All,
I have strings that represent my model and fields, like this
modelNameStr = 'MyModel'
fieldNameStr = 'modelField'
My model looks like this;
class MyModel(models.Model):
modelField = ForeignKey( ForeignModel )
...
What i want to do is create an instance of MyModel using the string variables, something like
model_instance = modelNameStr.objects.filter(fieldNameStr=ForeignModelInstance)
How can i do this?
Gath
model_instance = ContentType.objects.get(app_label=u'someapp', model=modelNameStr).model_class()(**{fieldNameStr: ForeignModelInstance})
Phew! Try saying that five times fast! But make sure you use the appropriate value for app_label.
Retrieving the model class you can use the get_model function from Django. Though you have to use a string like my_app.MyModel where 'my_app' is your django app which includes the model. Filtering field values can be achieved via a dict. Here an example:
from django.db.models import get_model
modelNameStr = 'my_app.MyModel'
fieldNameStr = 'modelField'
ModelClass = get_model(*model_class.split('.'))
filters = {fieldNameStr: ForeignModelInstance}
model_instance = ModelClass.objects.filter(**filters)