我需要在应用程序问题中执行模型答案的数据迁移.在该脚本中存在依赖性,因此我需要创建应用程序日记中的模型章的实例.所以,我把它编码如下:
def forwards(self, orm):
for answer_object in orm.Answer.objects.all():
#This Works.
blog, is_created = orm['blog.Post'].objects.get_or_create(title=answer_object.answer[:100])
blog.save()
#This DOES NOT work
chapter, is_created = orm['journal.Chapter'].objects.get_or_create(content_object=blog)
chapter.save()
#cleanup task, not relevant to this question below
answer_object.chapter_ptr = chapter
answer_object.save()
Run Code Online (Sandbox Code Playgroud)
但正如预期的那样,这会在"orm ['journal.Chapter']上引发错误.objects.get_or_create(content_object = blog)"
django.core.exceptions.FieldError: Cannot resolve keyword 'content_object' into field.
Run Code Online (Sandbox Code Playgroud)
这可能是由于content_object是GenericForeignKey,因此不允许进行某些操作.但我也尝试了其他替代方法来创建"章节"对象,比如
chapter = orm['journal.Chapter'](content_object=blog)
ERROR > TypeError: 'content_object' is an invalid keyword argument for this function
Run Code Online (Sandbox Code Playgroud)
和
chapter = orm.journal.Chapter(content_object=blog)
ERROR > AttributeError: The model …Run Code Online (Sandbox Code Playgroud) django data-migration instantiation django-south generic-foreign-key
我有以下概念模型:
class GenericAbstractBase(models.Model):
name = models.CharField(max_length=255)
staff = generic.GenericRelation(
"Staff",
content_type_field="content_type",
object_id_field="object_id",
)
class Meta:
abstract = True
class GenericModelA(GenericAbstractBase):
extra_a = models.CharField(max_length=255)
class GenericModelB(GenericAbstractBase):
extra_b = models.CharField(max_lenth=10)
class Staff(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
active = models.CharField(max_length=10, choices = ACTIVE_CHOICES)
limit = models.Q(app_label='staff', model='genericmodela') | models.Q(app_label='staff', model='genericmodelb')
content_type = models.ForeignKey(ContentType, limit_choices_to=limit)
object_id = models.PositiveIntegerField()
generic_object = generic.GenericForeignKey("content_type", "object_id")
Run Code Online (Sandbox Code Playgroud)
在Django v1.4和Django v1.5中,以下查询工作正常:
>>> ctype = ContentType.objects.get_for_model(GenericModelA)
>>> Staff.objects.filter(
content_type=ctype,
genericmodela__name__icontains="a"
)
>>> [<Staff: Abbott, Kaylee>, <Staff: Adams, Kay>, ... …Run Code Online (Sandbox Code Playgroud) 我正在研究Django的讨论应用程序,它有线程,帖子,回复和投票.投票使用通用外键和内容类型来确保用户只能在特定的线程/帖子/回复上投票一次.
投票模型如下所示:
VOTE_TYPE = (
(-1, 'DISLIKE'),
(1, 'LIKE'),
)
class Vote(models.Model):
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType,
limit_choices_to={"model__in": ("Thread", "Reply", "Post")},
related_name="votes")
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
vote = models.IntegerField(choices=VOTE_TYPE)
objects = GetOrNoneManager()
class Meta():
unique_together = [('object_id', 'content_type', 'user')]
Run Code Online (Sandbox Code Playgroud)
投票序列化器:
class VoteSerializer(serializers.ModelSerializer):
class Meta:
model = Vote
Run Code Online (Sandbox Code Playgroud)
处理投票的观点:
@api_view(['POST'])
def discussions_vote(request):
if not request.user.is_authenticated():
return Response(status=status.HTTP_404_NOT_FOUND)
data = request.DATA
if data['obj_type'] == 'thread':
content_type = ContentType.objects.get_for_model(Thread)
print content_type.id
info = {
'content_type': content_type.id,
'user': …Run Code Online (Sandbox Code Playgroud) django django-models django-contenttypes generic-foreign-key django-rest-framework
我在模型上使用Generic Relation并尝试使用Django Rest Framework对其进行序列化.但是,执行以下操作会给我一个属性错误:
'GenericForeignKey' object has no attribute 'field'
Run Code Online (Sandbox Code Playgroud)
models.py
class AdditionalInfo():
#other fields
seal_type = models.ForeignKey(ContentType,
related_name='seal'
)
seal_id = models.PositiveIntegerField(null=True)
seal = generic.GenericForeignKey(
'seal_type',
'seal_id')
Run Code Online (Sandbox Code Playgroud)
serializers.py
class AdditionalInfoSerializer():
seal = serializers.Field(source='seal')
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?我在django rest框架文档中找不到相关内容.
python django serialization generic-foreign-key django-rest-framework
我想为Comment具有GenericForeignKey关系的model()创建数据迁移.我的模型是根据django文档为contenttypes制作的.
楷模:
...
class NiceMeme(models.Model):
"""
Example model.
"""
name = models.CharField(max_length=140)
image = models.ImageField(upload_to=get_path_to_store_nice_meme_images)
class Comment(models.Model):
"""
Model to add comments to any other (non abstract) model.
"""
...
user = models.ForeignKey(ExtendedUser)
content = models.CharField(max_length=140)
content_type = models.ForeignKey(ContentType)
object_pk = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_pk')
Run Code Online (Sandbox Code Playgroud)
数据迁移:
...
def create_comment(apps, schema_editor):
...
nice_meme = NiceMeme.objects.create(name='Nice nice meme')
Comment.objects.create(
user=user,
content='Gott ist tot',
poster_username='Friedrich',
content_object=nice_meme
)
...
operations = [
migrations.RunPython(create_comment)
] …Run Code Online (Sandbox Code Playgroud) 符号.py
class Symbol(BaseModel):
name = models.CharField(max_length=30,)
class Meta:
abstract = True
class StockSymbol(Symbol):
market = models.CharField(max_length=10,)
my_daily_price = GenericRelation(MyDailyPrice)
Run Code Online (Sandbox Code Playgroud)
每日价格.py
class DailyPrice(BaseModel):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class Meta:
abstract = True
class MyDailyPrice(DailyPrice):
open = models.DecimalField(
max_digits=15,
decimal_places=2,
)
Run Code Online (Sandbox Code Playgroud)
我想做的是,
symbol = StockSymbol.objects.first()
MyDailyPrice.objects.filter(content_object=symbol)
Run Code Online (Sandbox Code Playgroud)
但它发生了错误:
FieldError: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation.
Run Code Online (Sandbox Code Playgroud)
StockSymbol已经有了 …
Django 的示例代码位于https://docs.djangoproject.com/es/1.9/ref/contrib/contenttypes/
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
Run Code Online (Sandbox Code Playgroud)
显示 object_id 不带db_index=True
虽然object_id可能会用于连接操作。
是db_index=True因为一些关于 GFK 的隐藏代码而被假设吗?或者我应该在需要时包含它?
我正在尝试在 django 中将外键转换为 GenericForeignKey。我计划在三个迁移中执行此操作:mig1、mig2、mig3。
迁移1(mig1)有以下代码
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('post_service', '0008_auto_20180802_1112'),
]
operations = [
migrations.AddField(
model_name='comment',
name='content_type',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType'),
),
migrations.AddField(
model_name='comment',
name='object_id',
field=models.PositiveIntegerField(null=True),
),
]
Run Code Online (Sandbox Code Playgroud)
迁移2(mig2)有以下代码
def change_posts_to_generic_key_comment(apps, schema_editor):
Comment = apps.get_model('post_service', 'Comment')
db_alias = schema_editor.connection.alias
comments = Comment.objects.using(db_alias).all()
for comment in comments:
Comment.objects.filter(id=comment.id).update(content_object=comment.post)
def reverse_change_posts_to_generic_key_comment(apps, schema_editor):
Comment = apps.get_model('post_service', 'Comment')
db_alias = schema_editor.connection.alias
comments = Comment.objects.using(db_alias).all()
for comment in comments:
Comment.objects.filter(id=comment.id).update(content_object=)
class Migration(migrations.Migration):
dependencies = [
('post_service', '0009_auto_20180802_1623'),
]
operations = [
migrations.RunPython(change_posts_to_generic_key_comment, …Run Code Online (Sandbox Code Playgroud) 我正在用头撞墙试图设置通用外键。我将发布尽可能多的代码,我将在一小时内重试。
我已经阅读了该文档一百万次,但它似乎没有帮助。
我认为这就是我正在做的事情。
def create_stream(request):
stream_form = StreamForm()
comment_form = CommentDataForm()
if request.POST:
stream_form = StreamForm(request.POST)
comment_form = CommentDataForm(request.POST)
if stream_form.is_valid() and comment_form.is_valid():
attempt = comment_form.save()
stream_form.save(commit=False)
stream_form.content_object = attempt
stream_form.save()
return HttpResponseRedirect('/main/')
else:
HttpResponse('Nope')
context = {'form1':stream_form, 'form2':comment_form}
template = 'nregistration.html'
return render(request, template, context)
Run Code Online (Sandbox Code Playgroud)
这些表单都是 ModelForm(为了便于使用,所以我可以使用保存功能)。他们看起来像这样
class StreamForm(forms.ModelForm):
class Meta:
model = Stream
exclude = ['object_id', 'content_object']
class CommentDataForm(forms.ModelForm):
class Meta:
model = CommentData
Run Code Online (Sandbox Code Playgroud)
我的相关课程看起来像这样
class Stream(models.Model):
uid = models.CharField(max_length=20, null=True, blank=True)
str_type = models.CharField(max_length=120, default='ABC')
creator = …Run Code Online (Sandbox Code Playgroud) 我在我的模型中定义了以下内容:
class TaskLink(models.Model):
task = model.ForeignKey(Task)
link_choices = (
models.Q(app_label="accounts", model="location"),
# Other models are also linked to here.
)
linked_content_type = \
models.ForeignKey(
ContentType,
limit_choices_to=link_choices
)
linked_object_id = models.PositiveIntegerField()
linked_object = \
generic.GenericForeignKey(
'linked_object_content_type',
'linked_object_id'
)
Run Code Online (Sandbox Code Playgroud)
该模型将Task对象与元组中的任何模型链接起来link_choices。在本例中,该accounts.Location模型在此列表中。
当删除一个Location对象导致相关对象的级联删除时,我的问题就出现了TaskLink。删除失败并出现以下错误消息:
django.core.exceptions.FieldError: Cannot resolve keyword 'object_id' into field. Choices are: id, linked_object, linked_object_content_type, linked_object_content_type_id, linked_object_id, task, task_id
Run Code Online (Sandbox Code Playgroud)
视图是django.views.generic.DeleteView仅包含pk_url_kwarg参数和模型集的实例(以及添加到调度方法中的权限装饰器);TaskLink在我将模型添加到混合中之前,它可以正常工作 linked_object_fine 。
我缺少什么?
编辑:这似乎可能是 Django 中的一个错误;当通过通用外键级联删除对象时,Django 会忽略传递给字段构造函数的字段名称字符串GenericForeignKey …