I encountered a problem with Django 1.7. When I want make my migration I raise this exception :
Models aren't loaded yet.
I tried solution said here but it doesn't work.
I saw this solution but I can't how do it with my models.
Error is due to person_type field on UserProfile Class. When I removed it migrations works.
class Typo_model(BaseModel):
key = models.CharField(max_length=32, db_index=True)
text = models.CharField(max_length=255)
class UserProfile(AbstractUser, BaseModel):
person_type = models.ForeignKey(Typo_model, queryset =
Typo_model.objects.filter(cle="person_type"), verbose_name="Person type")
I don't think you can set queryset on a ForeignKey. Purhaps limit_choices_to is what you are looking for. https://docs.djangoproject.com/en/1.7/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to
Like this:
person_type = models.ForeignKey(
Typo_model,
limit_choices_to={'cle': 'person_type'}
)
Related
I am little bit comfused. Lets say I have such models.
models.py:
class Company(models.Model):
name = models.CharField(blank=False, null=False)
class Game(models.Model):
developer = models.ForeignKey(Company, on_delete=models.CASCADE)
publishers = models.ManyToManyField(Company)
If I use next code:
current_company = Company.object.get(pk=1)
current_company.game_set.all()
as I understand it return all games of current_company, but what field (developer or publishers) Django used?
But this code wouldn't be valid, for precisely this reason. If you tried to run it, Django would tell you that there was a conflict in the reverse relation.
If you have two relationships pointing to the same model, you need to explicitly set related_name on one of them to avoid this conflict.
Django-allauth package creates a model SocialAccount, with a ForeignKey to User. I can't manage to prefetch this information in my queryset.
My model:
class Placerating(models.Model):
author = models.ForeignKey('auth.User', null=True, on_delete=models.SET_NULL)
Django-allauth model:
class SocialAccount(models.Model):
user = models.ForeignKey(allauth.app_settings.USER_MODEL, on_delete=models.CASCADE)
When I try to prefetch this data:
rating = Placerating.objects.all().prefetch_related('author__socialaccount')
I get the following error message:
AttributeError: Cannot find 'socialaccount' on User object, 'author__socialaccount' is an invalid parameter to prefetch_related()
Any clue ? Thanks!
I got my answer.
SocialAccount is a reverse Foreign key, so "_set" must be added at the end:
rating = Placerating.objects.all().prefetch_related('author__socialaccount_set')
I have a error being thrown when I navigate to my ListCreateAPIView base url:
url(r'^tests/$', TestList.as_view())
error:
coercing to Unicode: need string or buffer, NoneType found
which I believe to be related to the null=True in many of my CharField's throughout my various models. I ran into this error when attempting to add
Django Rest Framework Parsers to a ListAPIView like so:
class TestList(generics.ListCreateAPIView):
"""
"""
queryset = Tests.objects.all()
serializer_class = TestSerializer
filter_class = TestFilter
parser_classes = (FormParser, MultiPartParser)
class Courses(models.Model):
created = models.DateTimeField(default=timezone.now)
name = models.CharField(max_length=200, unique=True)
test = models.ForeignKey('Tests',
blank=True,
null=True,
on_delete=models.CASCADE)
class Tests(models.Model):
name = models.CharField(max_length=200)
it's either getting upset because of the null=True on the CharField's or perhaps because of the test foreign key I'm not totally sure? Would removing null=True and migrating solve this issue? Additionally, I should probably remove the null=True on CharField's anyway, would that be updated retroactively in the database?
I am not sure if I am doing it wrong or there is some issue when handling unique constraint when working with GenericForeign Relations in Django.
When I try to save an object (in Admin for example) I get unique constraint error (raises 500) form database but not ValidationError on Admin (UI).
Below is my code snippet,
I have one generic relation model as below,
class Targeting(models.Model):
TARGETING_CHOICES = (
('geo', "Geo targeting"),
('other', "Other targeting"),
)
targeting_type = models.CharField(max_length=64, choices=TARGETING_CHOICES, null=False)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class Meta:
unique_together = ('content_type', 'object_id', 'targeting_type')
And my other model using it is,
class MyModel(models.Model):
name = models.CharField(max_length=60, db_index=True)
targeting = GenericRelation('Targeting')
Exception Raised:
duplicate key value violates unique constraint "mymodel_targeting_targeting_type_0dff10ee_uniq"
DETAIL: Key (targeting_type, content_type_id, object_id)=(geo, 18, 188) already exists.
Is there something wrong with way I implemented it ? or something is not meant to used like this ?
Any sort of help is really appreciated. Thanks
You won't receive ValidationError here, because it can't be validated without additional query and django won't create that query by itself. If you need to have that validation, you need to write it by yourself.
I am using Django REST Framework. I have two models, Sites and Statuses.
class Sites(models.Model):
site_id = models.AutoField(primary_key=True)
status = models.ForeignKey(Statuses, models.DO_NOTHING, blank=True, null=True)
class Statuses(models.Model):
status_id = models.AutoField(primary_key=True)
description = models.CharField(max_length=255, blank=True, null=True, unique=True)
class Meta:
managed = True
db_table = 'Statuses'
I would like to be able to perform a GET on sites, and have the Statuses.description field returned (instead of Statuses.status_id). Also, I would like it so that either status_id or description may be used interchangeably in a POST to create a new site. Where does this type of functionality belong (serializer, models, etc...)?
I know I can accomplish the first part of my question by adding a property to the Sites model and then referencing this field in the Sites serializer.
#property
def status(self):
return self.row_status.description
However I thought the convention of a Model is that it should be a 1:1 representation of the database table. Is there a better way to do this?
This fits well in the serializer, like this:
class SitesSerializer(serializers.ModelSerializer):
description = serializers.CharField(source='status.description')
class Meta:
model = Sites
fields = ('site_id', 'description')
(But the status field should probably not have null=True set.)