class question(models.Model):
question_id = models.IntegerField()
choice = models.CharField(max_length=100)
tags = models.ArrayField(models.CharField(max_length=100))
ERROR:
packages\djongo\models\fields.py", line 116, in _validate_container
for field in self.model_container._meta._get_fields(reverse=False):
AttributeError: 'CharField' object has no attribute '_meta'
I want to add a ArrayField in my models using djongo models. i hope 'tags' looks like ['tag1', 'tag2', 'tag3' ...]. But djongo requeirs model_container, but i only want an array contains strings, not a model ,please help~~
I was experiencing a similar situation: wanted to create an IntegerField array. I solved it with this workaround:
Create an intermediate model which stores your field.
For example, for my use case (with integers that represent quantity by each second) I created a model called Second which holds an attribute called data of type models.IntegerField():
class Second(models.Model):
data = models.IntegerField(null=False)
class Meta:
abstract = True
class ParentModel(models.Model):
_id = models.ObjectIdField()
by_second = models.ArrayField(
model_container=Second
)
objects = models.DjongoManager()
So I guess in your case you could use the same but changing models.IntegerField()by models.CharField(max_length=100)
I know it has been a long time since the question was asked, but I hope this helps someone having this issue :)
Related
I have two models, one is pointing to other model.
class ModelA(models.Model):
field1 = models.CharField()
field2 = models.CharField()
class ModelB(models.Model):
field3 = models.CharField()
field4 = models.CharField()
modela = models.ForeignKey(ModelA)
I am using Django REST for data manipulation. I am trying to insert data to ModelA and ModelB using one ajax call. For one entry in ModelA, I have a list of entries in ModelB. So my ajax data is,
ajax_data = {modela: {....}, modelb: [{...}, {...}, ...]}
When I am using only one model, I am able to save, otherwise I am not. Can I save two related model in one one POST request?
Yes. I'm going to use the non-accepted answer from this question.
The Django docs state that you need to save the dependent model (A, in your case), before you can save the related model (B, in your case.)
Note that you must save an object before it can be assigned to a
foreign key relationship. For example, creating an Article with
unsaved Reporter raises ValueError:
>>> r3 = Reporter(first_name='John', last_name='Smith', email='john#example.com')
>>> Article.objects.create(headline="This is a test", pub_date=date(2005, 7, 27), reporter=r3)
Traceback (most recent call last):
...
ValueError: save() prohibited to prevent data loss due to unsaved related object 'reporter'.
As the other answer says - you can either do this in two POSTs or handle it in the view. It's hard to give specifics without seeing your view code, but the DRF docs have this covered.
I've adapted Robert's code for use here. If it was an accepted answer, I'd just have linked it as a duplicate.
class ASerializer(serializers.ModelSerializer):
class Meta:
model = ModelA
fields = ('field1', 'field1')
class BSerializer(serializers.ModelSerializer):
bclass = ASerializer()
class Meta:
model = ModelB
fields = ('field1', 'field2', 'etc')
views.py
import generics
class BCreateAPIView(generics.CreateAPIView):
model = ModelB
serializer_class = BSerializer
I'm working in Django 1.8. I have models like this:
class School(models.Model):
code = models.CharField(primary_key=True)
name = models.CharField(max_length=200)
class Meta:
app_label = 'frontend'
class SchoolStatusOnDate(models.Model):
school = models.ForeignKey(School)
date = models.DateField()
setting = models.IntegerField()
I want to retrieve all the statuses associated with a particular school, and I think I should be able to do it using _set as described here, but it isn't working. This is my code:
s = School.objects.filter(code='A81018')
now = datetime.datetime.now()
SchoolStatusOnDate.objects.create(school=s, date=now, setting=4)
print s.schoolStatusOnDate_set.all()
But this gives me the following error on the final line:
AttributeError: 'School' object has no attribute 'schoolStatusOnDate_set'
What am I doing wrong?
schoolStatusOnDate_set should be lowercase.
From Django documentation: Following relationships “backward”:
If a model has a ForeignKey, instances of the foreign-key model will have access to a Manager that returns all instances of the first model. By default, this Manager is named FOO_set, where FOO is the source model name, lowercased.
(emphasis mine)
I am stuck on trying to solve an issue with the Serializers and related fields using the django-rest-framework. Currently I have a model that looks like this:
class DataSetModel(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
class DataPointModel(models.Model):
dataSet = models.ForeignKey(DataSetModel, related_name='dataPoints')
label = models.CharField(max_length=200)
My serializers look like this:
class DataPointSerializer(serializers.ModelSerializer):
class Meta:
model = DataPointModel
fields = ('pk','label')
class DataSetSerializer(serializers.ModelSerializer):
dataPoints = DataPointSerializer(many=True, read_only=True)
class Meta:
model = DataSetModel
fields = ('pk','title')
The problem I am having is when I try to change the "many=False" in the serializer produces this error:
Got AttributeError when attempting to get a value for field label on
serializer DataPointSerializer. The serializer field might be named
incorrectly and not match any attribute or key on the RelatedManager
instance. Original exception text was: 'RelatedManager' object has no
attribute 'label'.
Since this is only ever one model object (one-to-many relationship), I want to get the result as a single object vs a list of one object.
Am I doing this the right way? I thought that turning the "many=False" it would fetch the first record in an nested query.
Any insight would be greatly appreciated.
You can't set many=False, because dataPoints is a related field that returns a queryset containing a list of instances, not just an instance.
When you do DataPointModel.dataPoints that returns a queryset, it can't returns just an instance. So setting many=False, it wouldn't get the first element of the list.
So the solve I came to was refactoring my models with where the Foreign Keys are attached.
Here is the fix I implemented:
class DataSetModel(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
dataPoint = models.ForeignKey(DataPointModel)
class DataPointModel(models.Model):
label = models.CharField(max_length=200)
Moving it to the DataSetModel automatically joins the data model if you set 'many=False' in the Serializer object.
Write your DataPointModel as below. It should work then
class DataPointModel(models.Model):
dataSet = models.OneToOneField(DataSetModel, related_name='dataPoints')
label = models.CharField(max_length=200)
Problem:
I'm using Django Rest Framework and i want to fetch all models with the relationships included, like this:
TestModel.objects.all()
My model looks like this:
class TestModel(models.Model):
name = models.CharField(max_length=32)
related_model = models.ForeignKey(TestRelation)
Problem is, i only get the Primary Keys for related_model but i need the whole related_model!
I'm using the ListCreateAPIView, with the above queryset (TestModel.objects.all()) and the most basic form of the ModelSerializer.
I tried the PrimaryKeyRelatedField but i get the same result..
Thanks!
Just create serializer for your related model:
class TestRelationSerializer(serializers.ModelSerializer):
class Meta:
meta = TestRelation
and use is as field in TestModelSerializer:
class TestModelSerializer(serializers.ModelSerializer):
related_model = TestRelationSerializer()
You can also do it other way around, by using TestModelSerializer as field in TestRelationSerializer with many set to true:
class TestRelationSerializer(serializers.ModelSerializer):
testmodel_set = TestModelSerializer(many=True)
just remember, you can't do both at once due to infinite recursion it makes.
I'm new in using GenericForeignKey, and I couldn't make it to work in a query statement. The tables are roughly like the following:
class Ticket(models.Model):
issue_ct = models.ForeignKey(ContentType, related_name='issue_content_type')
issue_id = models.PositiveIntegerField(null=True, blank=True)
issue = generic.GenericForeignKey('issue_ct', 'issue_id')
class Issue(models.Model):
scan = models.ForeignKey(Scan)
A scan creates one issue, an issue generates some tickets, and I made Issue as a foreign key to Ticket table. Now I have a Scan object, and I want to query for all the tickets that related to this scan. I tried this first:
tickets = Tickets.objects.filter(issue__scan=scan_obj)
which doesn't work. Then I tried this:
issue = Issue.objects.get(scan=scan_obj)
content_type = ContentType.objects.get_for_model(Issue)
tickets = Tickets.objects.filter(content_type=content_type, issue=issue)
Still doesn't work. I need to know how to do these kind of queries in django? Thanks.
The Ticket.issue field you've defined will help you go from a Ticket instance to the Issue it's attached to, but it won't let you go backwards. You're close with your second example, but you need to use the issue_id field - you can't query on the GenericForeignKey (it just helps you retrieve the object when you have a Ticket instance). Try this:
from django.contrib.contenttypes.models import ContentType
issue = Issue.objects.get(scan=scan_obj)
tickets = Ticket.objects.filter(
issue_id=issue.id,
issue_ct=ContentType.objects.get_for_model(issue).id
)
Filtering across a GenericForeignKey can by creating a second model that shares the db_table with Ticket. First split up Ticket into an abstract model and concrete model.
class TicketBase(models.Model):
issue_ct = models.ForeignKey(ContentType, related_name='issue_content_type')
issue_id = models.PositiveIntegerField(null=True, blank=True)
class Meta:
abstract = True
class Ticket(TicketBase):
issue = generic.GenericForeignKey('issue_ct', 'issue_id')
Then create a model that also subclasses TicketBase. This subclass will have all the same fields except issue which is instead defined as a ForeignKey. Adding a custom Manager allows it to be filtered to just a single ContentType.
Since this subclass does not need to be synced or migrated it can be created dynamically using type().
def subclass_for_content_type(content_type):
class Meta:
db_table = Ticket._meta.db_table
class Manager(models.Manager):
""" constrain queries to a single content type """
def get_query_set(self):
return super(Manager, self).get_query_set().filter(issue_ct=content_type)
attrs = {
'related_to': models.ForeignKey(content_type.model_class()),
'__module__': 'myapp.models',
'Meta': Meta,
'objects': Manager()
}
return type("Ticket_%s" % content_type.name, (TicketBase,), attrs)